问:
Default values in Haskell data types
When you define a class in a object-oriented language it usually sets the default values for the member variables. Is there any mechanism in Haskell to do the same thing in record types? And a follow up question: If we don't know from the very start all the values for a data constructor but we obtain them from IO interaction can we build the type using something like the builder pattern from OOP?

Thanks in advance

答:
A common idiom is to define a default value.

```<code>data A = A { foo :: Int , bar :: String }

defaultA :: A
defaultA = A{foo = 0, bar = ""}
</code>```

This can be then (purely) "updated" later on with real values.

```<code>doSomething :: Bool -> A
doSomething True  = defaultA{foo = 32}
doSomething False = defaultA{bar = "hello!"}
</code>```

Pseudocode example:

```<code>data Options = O{ textColor :: Bool, textSize :: Int, ... }

defaultOptions :: Options
defaultOptions = O{...}

doStuff :: Options -> IO ()
doStuff opt = ...

main :: IO ()
main = do
     ...
     -- B&W, but use default text size
     doStuff defaultOptions{ color = False }
</code>```

If there are no sensible default values, you can wrap the field values in Maybe.

If you feel adventurous, you can even use a more advanced approach to statically separate "intermediate" options values, which can lack a few fields, from "finalized" ones, which must have all the fields. (I'd not recommend this to Haskell beginners, though.)

Title: Default values in Haskell data types

Body:
A common idiom is to define a default value.

data A = A { foo :: Int , bar :: String }

defaultA :: A
defaultA = A{foo = 0, bar = ""}

This can be then (purely) "updated" later on with real values.

doSomething :: Bool -> A
doSomething True  = defaultA{foo = 32}
doSomething False = defaultA{bar = "hello!"}

Pseudocode example:

data Options = O{ textColor :: Bool, textSize :: Int, ... }

defaultOptions :: Options
defaultOptions = O{...}

doStuff :: Options -> IO ()
doStuff opt = ...

main :: IO ()
main = do
     ...
     -- B&W, but use default text size
     doStuff defaultOptions{ color = False }

If there are no sensible default values, you can wrap the field values in Maybe.

If you feel adventurous, you can even use a more advanced approach to statically separate "intermediate" options values, which can lack a few fields, from "finalized" ones, which must have all the fields. (I'd not recommend this to Haskell beginners, though.)


来源: stackexchange

问:
PHP Coding Style Function vs Passing Variables
A bit new to the whole PHP thing.

Just wanna ask, which is better in regards to performance and security. I know both has its pros and cons, but just cant seem to come to a conclusion on which could be better for overall performance and security.

Use a PHP file with loads of functions. So every page I have will "include" the function php file, thus functions can be called in any given page.

OR

Have a PHP file that accept parameter input(not sure if that is what you call it). For example function.PHP?id=100

Any comments?

Thanks everyone :)

答:
The second method is preferred: one index.php file which drives the entire application/website.

As for breaking down the application,
you'll use both: parameters in the URL, to decide what is to be done, and helper functions which receive parameters and do their job.

The challenge is to break down the "big problem" in smaller, reusable "sub-problems" and wrap each in a reusable function.

After that, solving the "big problem" is a matter of sticking together function calls, like you do in a puzzle game.

Now, that was the way to go at your beginner level, at a more advanced level you would break it down in an OOP manner, to take advantage of autoloading (read my response there for details).

Right in-between the two levels of experience, you could try first to use a procedural php framework like http://www.limonade-php.net/, and second to understand its code and learn from it. This should put you on the right track for more advanced uses of PHP.

None of your presented options have something particular in respect to security or performance, they're both the same. Breaking it down in functions is a matter of code reusability and maintainability. That being said, the OOP is still better in any regards (again, I'll have to point at my other answer).

As I said, you'll use both, AND you'll have to validate the input (that is, $_REQUEST $_GET, $_POST, $_COOKIE, $_SESSION, $_FILE, (some elements from) $_SERVER). Be careful with XSS (basically, you'll use either strip_tags() or htmlentities() or a combination of the two). That's about the security aspect.

ContentLicense: CC BY-SA 2.5


问:
Create Border around image when clicked in JavaScript?
I'm working on an assignment for school and have been trying to get the code to run as it is supposed to. At this point all I need is for the Onclick to work. I try to put a border around each thumbnail image that is clicked and then have the border removed once another image is clicked. I have looked at multiple resources, but can't seem to get this to work at all. If anyone can provide assistance it would be really appreciated. I am extremely new to JavaScript and am pretty lost with the resources I've been given. My resolution needs to be purely in JavaScript without any JQuery.

// JavaScript Document //
var imgArray = new Array(
  //list of slides
  'chestnutp.jpg',
  'chestnuts.jpg',
  'elephant.jpg',
  'fall.jpg',
  'leaves.jpg'
);
var imgPath = "img/";

function swapImage(imgID) { //pulls image to larger area..
  var theImage = document.getElementById('largeImage');
  var newImg;
  newImg = imgArray[imgID];
  theImage.src = imgPath + newImg;
  var element = document.getElementById("id20");
  element.innerHTML = "New Fall Photo Gallery"; //Additional change to DOM; changes original name
}
var captionArray = [
  //list of captions
  'A chestnut coming out of a plant on a fall day.',
  'A bundle of chestnuts on the ground on a fall day.',
  'An Elephant walking on an African Fall evening.',
  'A fall display with flowers and pumpkins.',
  'Looking up at the leaves on a fall day.'
];

function swapCaption(ID) { //creates caption when larger image is shown
  var theCaption = document.getElementById('caption');
  var newCaption;
  newCaption = captionArray[ID];
  theCaption.innerHTML = newCaption;
}

function mark(ID) { //creates border
  document.getElementById(ID).style.border = "2px solid orange";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@charset "utf-8";

/* CSS Document */

body {
  background-color: #322F2F;
  font-family: Gotham, "Helvetica Neue", Helvetica, Arial, sans-serif;
}

* {
  box-sizing: border-box;
}

.col-1 {
  width: 8.33%;
}

.col-2 {
  width: 16.66%;
}

.col-3 {
  width: 25%;
}

.col-4 {
  width: 33.33%;
}

.col-5 {
  width: 41.66%;
}

.col-6 {
  width: 50%;
}

.col-7 {
  width: 58.33%;
}

.col-8 {
  width: 66.66%;
}

.col-9 {
  width: 75%;
}

.col-10 {
  width: 83.33%;
}

.col-11 {
  width: 91.66%;
}

.col-12 {
  width: 100%;
}

[class*="col-"] {
  float: left;
}

.row:after {
  content: "";
  clear: both;
  display: block;
}

#wrapper {
  height: auto;
  width: 60%;
  margin: auto;
}

h1 {
  font-size: 1.6em;
  color: #fff;
  text-align: center;
}

#thumbnails {
  height: 20%;
  width: 100%;
}

#thumbnails>img:hover {
  border: 1px #9D9C9C solid;
}

.thumbDown {
  border: none;
}

.thumbUp {
  border: 1px #9D9C9C solid;
}

.largeImage {
  height: 100%;
  width: 100%;
}

.caption {
  font-size: .9em;
  height: 25px;
  width: 100%;
  color: #fff;
}</code>```

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Fall Air Photo Gallery</title>

  <link rel="stylesheet" type="text/css" href="css/style.css" />

Fall Air Photo Gallery

```

答:
Your onclick trigger is not selecting any existing id. It is instead searching for an element with the number you entered as an id.

Your current onclick event:

```<code>onclick="mark(1)"
</code>```

Is searching for an element with an id equal to one (ex: id="1")

It should instead be triggering the mark() function using "this" to tell javascript to run the function on the current element.

your onclick events should be changed to:

```<code>onclick="mark(this)"
</code>```

And update your mark() function to:

```<code>function mark(currentEl) {
    // Retreives the id of current element that is clicked
    var id = currentEl.id;

    // Apply the border
    document.getElementById(id).style.border="2px solid orange";
}
</code>```

Once you apply this change a border will appear, however, it will wont go away once clicked on another image. I am assuming you would like the border to appear on current image clicked only to highlight the active image and be removed from the previous.

Alternate function to only highlight the active image:
I am using a conditional here for an easier understanding. @Paul T's approach is a great alternative if you are familiar with for loops.

```<code>// set an empty variable to compare later
var previousEl;

function mark(currentEl) {

    // Retrieves the id of current element that is clicked
    var id = currentEl.id;

    /**
    * Checks to see if a previous element has been clicked
    * if it was, it will remove the border from the previous and apply it to the current element
    */
    if(previousEl){
        previousEl.style.border = "unset"; // css unset border
        currentEl.style.border = "2px solid orange"; // apply border to current element
        previousEl = document.getElementById(id); // assign current element id to previousEl variable
    } else {
        currentEl.style.border = "2px solid orange";
        previousEl = document.getElementById(id);
    }
}
</code>```

Below is a working snippet using the alternate function.

// JavaScript Document
var imgArray = new Array(
    //list of slides
    '/400/200/abstract',
    '/400/200/abstract',
    '/400/200/abstract',
    '/400/200/abstract',
    '/400/200/abstract'
);
var imgPath = "http://lorempixel.com";

function swapImage(imgID) { //pulls image to larger area..
    var theImage = document.getElementById('largeImage');
    var newImg;
    newImg = imgArray[imgID];
    theImage.src = imgPath + newImg;
    var element = document.getElementById("id20");
    element.innerHTML = "New Fall Photo Gallery"; //Additional change to DOM; changes original name
}
var captionArray = [
    //list of captions
    'A chestnut coming out of a plant on a fall day.',
    'A bundle of chestnuts on the ground on a fall day.',
    'An Elephant walking on an African Fall evening.',
    'A fall display with flowers and pumpkins.',
    'Looking up at the leaves on a fall day.'
];

function swapCaption(ID) { //creates caption when larger image is shown
    var theCaption = document.getElementById('caption');
    var newCaption;
    newCaption = captionArray[ID];
    theCaption.innerHTML = newCaption;
}

// set an empty variable to compare later
var previousEl;

function mark(currentEl) {

    // Retreives the id of current element that is clicked
    var id = currentEl.id;

    /**
    * Checks to see if a previous element has been clicked
    * if it was, it will remove the border from the previous and apply it to the current element
    */
    if(previousEl){
        previousEl.style.border = "unset"; // css unset border
        currentEl.style.border = "2px solid orange"; // apply border to current element
        previousEl = document.getElementById(id); // assign current element id to previousEl variable
    } else {
        currentEl.style.border = "2px solid orange"; //
        previousEl = document.getElementById(id);
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* CSS Document */

body {
    background-color: #322F2F;
    font-family: Gotham, "Helvetica Neue", Helvetica, Arial, sans-serif;
}

* {
    box-sizing: border-box;
}

.col-1 {
    width: 8.33%;
}

.col-2 {
    width: 16.66%;
}

.col-3 {
    width: 25%;
}

.col-4 {
    width: 33.33%;
}

.col-5 {
    width: 41.66%;
}

.col-6 {
    width: 50%;
}

.col-7 {
    width: 58.33%;
}

.col-8 {
    width: 66.66%;
}

.col-9 {
    width: 75%;
}

.col-10 {
    width: 83.33%;
}

.col-11 {
    width: 91.66%;
}

.col-12 {
    width: 100%;
}

[class*="col-"] {
    float: left;
}

.row:after {
    content: "";
    clear: both;
    display: block;
}

#wrapper {
    height: auto;
    width: 60%;
    margin: auto;
}

h1 {
    font-size: 1.6em;
    color: #fff;
    text-align: center;
}

#thumbnails {
    height: 20%;
    width: 100%;
}

#thumbnails>img:hover {
    border: 1px #9D9C9C solid;
}

.thumbDown {
    border: none;
}

.thumbUp {
    border: 1px #9D9C9C solid;
}

.largeImage {
    height: 100%;
    width: 100%;
}

.caption {
    font-size: .9em;
    height: 25px;
    width: 100%;
    color: #fff;
}</code>```

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Fall Air Photo Gallery</title>

    <link rel="stylesheet" type="text/css" href="css/style.css" />

Fall Air Photo Gallery

```

ContentLicense: CC BY-SA 3.0

Body:
I'm working on an assignment for school and have been trying to get the code to run as it is supposed to. At this point all I need is for the Onclick to work. I try to put a border around each thumbnail image that is clicked and then have the border removed once another image is clicked. I have looked at multiple resources, but can't seem to get this to work at all. If anyone can provide assistance it would be really appreciated. I am extremely new to JavaScript and am pretty lost with the resources I've been given. My resolution needs to be purely in JavaScript without any JQuery.

// JavaScript Document //
var imgArray = new Array(
  //list of slides
  'chestnutp.jpg',
  'chestnuts.jpg',
  'elephant.jpg',
  'fall.jpg',
  'leaves.jpg'
);
var imgPath = "img/";

function swapImage(imgID) { //pulls image to larger area..
  var theImage = document.getElementById('largeImage');
  var newImg;
  newImg = imgArray[imgID];
  theImage.src = imgPath + newImg;
  var element = document.getElementById("id20");
  element.innerHTML = "New Fall Photo Gallery"; //Additional change to DOM; changes original name
}
var captionArray = [
  //list of captions
  'A chestnut coming out of a plant on a fall day.',
  'A bundle of chestnuts on the ground on a fall day.',
  'An Elephant walking on an African Fall evening.',
  'A fall display with flowers and pumpkins.',
  'Looking up at the leaves on a fall day.'
];

function swapCaption(ID) { //creates caption when larger image is shown
  var theCaption = document.getElementById('caption');
  var newCaption;
  newCaption = captionArray[ID];
  theCaption.innerHTML = newCaption;
}

function mark(ID) { //creates border
  document.getElementById(ID).style.border = "2px solid orange";
}

@charset "utf-8";

/* CSS Document */

body {
  background-color: #322F2F;
  font-family: Gotham, "Helvetica Neue", Helvetica, Arial, sans-serif;
}

* {
  box-sizing: border-box;
}

.col-1 {
  width: 8.33%;
}

.col-2 {
  width: 16.66%;
}

.col-3 {
  width: 25%;
}

.col-4 {
  width: 33.33%;
}

.col-5 {
  width: 41.66%;
}

.col-6 {
  width: 50%;
}

.col-7 {
  width: 58.33%;
}

.col-8 {
  width: 66.66%;
}

.col-9 {
  width: 75%;
}

.col-10 {
  width: 83.33%;
}

.col-11 {
  width: 91.66%;
}

.col-12 {
  width: 100%;
}

[class*="col-"] {
  float: left;
}

.row:after {
  content: "";
  clear: both;
  display: block;
}

#wrapper {
  height: auto;
  width: 60%;
  margin: auto;
}

h1 {
  font-size: 1.6em;
  color: #fff;
  text-align: center;
}

#thumbnails {
  height: 20%;
  width: 100%;
}

#thumbnails>img:hover {
  border: 1px #9D9C9C solid;
}

.thumbDown {
  border: none;
}

.thumbUp {
  border: 1px #9D9C9C solid;
}

.largeImage {
  height: 100%;
  width: 100%;
}

.caption {
  font-size: .9em;
  height: 25px;
  width: 100%;
  color: #fff;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Fall Air Photo Gallery</title>

  <link rel="stylesheet" type="text/css" href="css/style.css" />

Fall Air Photo Gallery

Body:
Your onclick trigger is not selecting any existing id. It is instead searching for an element with the number you entered as an id.

Your current onclick event:

onclick="mark(1)"

Is searching for an element with an id equal to one (ex: id="1")

It should instead be triggering the mark() function using "this" to tell javascript to run the function on the current element.

your onclick events should be changed to:

onclick="mark(this)"

And update your mark() function to:

function mark(currentEl) {
    // Retreives the id of current element that is clicked
    var id = currentEl.id;

    // Apply the border
    document.getElementById(id).style.border="2px solid orange";
}

Once you apply this change a border will appear, however, it will wont go away once clicked on another image. I am assuming you would like the border to appear on current image clicked only to highlight the active image and be removed from the previous.

Alternate function to only highlight the active image:
I am using a conditional here for an easier understanding. @Paul T's approach is a great alternative if you are familiar with for loops.

// set an empty variable to compare later
var previousEl;

function mark(currentEl) {

    // Retrieves the id of current element that is clicked
    var id = currentEl.id;

    /**
    * Checks to see if a previous element has been clicked
    * if it was, it will remove the border from the previous and apply it to the current element
    */
    if(previousEl){
        previousEl.style.border = "unset"; // css unset border
        currentEl.style.border = "2px solid orange"; // apply border to current element
        previousEl = document.getElementById(id); // assign current element id to previousEl variable
    } else {
        currentEl.style.border = "2px solid orange";
        previousEl = document.getElementById(id);
    }
}

Below is a working snippet using the alternate function.

// JavaScript Document
var imgArray = new Array(
    //list of slides
    '/400/200/abstract',
    '/400/200/abstract',
    '/400/200/abstract',
    '/400/200/abstract',
    '/400/200/abstract'
);
var imgPath = "http://lorempixel.com";

function swapImage(imgID) { //pulls image to larger area..
    var theImage = document.getElementById('largeImage');
    var newImg;
    newImg = imgArray[imgID];
    theImage.src = imgPath + newImg;
    var element = document.getElementById("id20");
    element.innerHTML = "New Fall Photo Gallery"; //Additional change to DOM; changes original name
}
var captionArray = [
    //list of captions
    'A chestnut coming out of a plant on a fall day.',
    'A bundle of chestnuts on the ground on a fall day.',
    'An Elephant walking on an African Fall evening.',
    'A fall display with flowers and pumpkins.',
    'Looking up at the leaves on a fall day.'
];

function swapCaption(ID) { //creates caption when larger image is shown
    var theCaption = document.getElementById('caption');
    var newCaption;
    newCaption = captionArray[ID];
    theCaption.innerHTML = newCaption;
}

// set an empty variable to compare later
var previousEl;

function mark(currentEl) {

    // Retreives the id of current element that is clicked
    var id = currentEl.id;

    /**
    * Checks to see if a previous element has been clicked
    * if it was, it will remove the border from the previous and apply it to the current element
    */
    if(previousEl){
        previousEl.style.border = "unset"; // css unset border
        currentEl.style.border = "2px solid orange"; // apply border to current element
        previousEl = document.getElementById(id); // assign current element id to previousEl variable
    } else {
        currentEl.style.border = "2px solid orange"; //
        previousEl = document.getElementById(id);
    }
}

/* CSS Document */

body {
    background-color: #322F2F;
    font-family: Gotham, "Helvetica Neue", Helvetica, Arial, sans-serif;
}

* {
    box-sizing: border-box;
}

.col-1 {
    width: 8.33%;
}

.col-2 {
    width: 16.66%;
}

.col-3 {
    width: 25%;
}

.col-4 {
    width: 33.33%;
}

.col-5 {
    width: 41.66%;
}

.col-6 {
    width: 50%;
}

.col-7 {
    width: 58.33%;
}

.col-8 {
    width: 66.66%;
}

.col-9 {
    width: 75%;
}

.col-10 {
    width: 83.33%;
}

.col-11 {
    width: 91.66%;
}

.col-12 {
    width: 100%;
}

[class*="col-"] {
    float: left;
}

.row:after {
    content: "";
    clear: both;
    display: block;
}

#wrapper {
    height: auto;
    width: 60%;
    margin: auto;
}

h1 {
    font-size: 1.6em;
    color: #fff;
    text-align: center;
}

#thumbnails {
    height: 20%;
    width: 100%;
}

#thumbnails>img:hover {
    border: 1px #9D9C9C solid;
}

.thumbDown {
    border: none;
}

.thumbUp {
    border: 1px #9D9C9C solid;
}

.largeImage {
    height: 100%;
    width: 100%;
}

.caption {
    font-size: .9em;
    height: 25px;
    width: 100%;
    color: #fff;
}

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>Fall Air Photo Gallery</title>
    <!--Change title-->
    <link rel="stylesheet" type="text/css" href="css/style.css" />
    <script src="js/image-gallery.js"></script>

</head>

<body>
    <div id="wrapper">
        <div class="row">
            <div class="col-12">
                <h1 id="id20">Fall Air Photo Gallery</h1>
                <!--Change Header-->
            </div>
        </div>
        <div class="row">
            <div class="col-12">
                <div id="thumbnails">
                    <img src="http://lorempixel.com/400/200/abstract" id="chestnutp" onclick="mark(this)" width="19.375%" height="19.5%" alt="Chestnut in Plant" onmouseover="swapImage(0); swapCaption(0)" />
                    <!--onmouseover will switch images on hover-->
                    <!--Onclick used to put border behind clicked imaged-->
                    <img src="http://lorempixel.com/400/200/abstract" id="chestnuts" onclick="mark(this)" width="19.375%" height="19.5%" alt="Chestnuts on the Ground" onmouseover="swapImage(1); swapCaption(1)" />
                    <img src="http://lorempixel.com/400/200/abstract" id="elephant" onclick="mark(this)" width="19.375%" height="19.5%" alt="Elephant walking the African fall sunset" onmouseover="swapImage(2); swapCaption(2)" />
                    <img src="http://lorempixel.com/400/200/abstract" id="fall" onclick="mark(this)" width="19.375%" height="19.5%" alt="Fall display on a fall day" onmouseover="swapImage(3); swapCaption(3)" />
                    <img src="http://lorempixel.com/400/200/abstract" id="leaves" onclick="mark(this)" width="19.375%" height="19.5%" alt="Leaves on a Fall Day" onmouseover="swapImage(4); swapCaption(4)" />
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-12">
                <div id="mainImage">
                    <img id="largeImage" src="" width="100%" height="100%" alt="" />
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-12">
                <div class="caption">
                    <p id="caption"></p>

                </div>
            </div>
        </div>
    </div>
</body>

</html>


问:
Change Badge icon when notified
I'm using Xamarin Forms and I manage to send notifications to my applications in both iOS and Android using Firebase. I want to change the Badge icon every time a notification arrives, with the application in the background.
Similar to Twitter or Whatsapp.

How can I change the Badge of my application when my application is in the background?

答:
For Android I use ShortcutBadger https://github.com/leolin310148/ShortcutBadger

But it's up to the Phone's Launcher to decide if it will show the badge and for me it wont show on the Emulator but it does work on my phone.

As for iOS I haven't looked into this yet so if you find one please do tell.

Title: Change Badge icon when notified


问:
How to hide my HTML drop-down menu correctly?
I made a drop-down menu consisting of a HTML input/button and some more buttons as drop-down menu items. The menu is shown as soon as hovered over the main button

```<code><div class="dropdown">
    <button id="dropdown-wifi" class="extended-button" onclick="showDropDown()">Available WiFi Hot Spots</button>
    <div id="ssid-dropdown" class="dropdown-content">
        <!-- drop-down menu items dynamically created by JavaScript -->
    </div>
</div>
</code>```

This is the hover event in CSS:

```<code>.dropdown:hover .dropdown-content {
    display: block;
}
</code>```

The JavaScript code that hides and later 'should' show again:

```<code>function showDropDown() {
    document.getElementById("ssid-dropdown").style.display = 'block';
}

function hideDropDown() {
    document.getElementById("ssid-dropdown").style.display = 'none';
}
</code>```

Now, the drop-down menu is properly shown as soon as I hover over the main button. But when selecting an item, I call hideDropDown() to hide the menu even if not hovered outside of the items.

I notified that as soon as the hideDropDown() function is called, the following is added in the CSS window of Chrome's debug windows:

```<code>element.style {
    display: none;
}
</code>```

I guess, that is a kind of CSS generated because my JavaScript function call of hideDropDown(). However, as soon as this element.stlye is occuring, the hovering/show of the drop-down menu doesn't work anymore.

Any ideas how to solve this issue?

答:
hello to my dear friend you can simply just use jquery like this :

$(".dropdown").show() OR $(".dropdown").hide()

Body:
I made a drop-down menu consisting of a HTML input/button and some more buttons as drop-down menu items. The menu is shown as soon as hovered over the main button

    <button id="dropdown-wifi" class="extended-button" onclick="showDropDown()">Available WiFi Hot Spots</button>

This is the hover event in CSS:

.dropdown:hover .dropdown-content {
    display: block;
}

The JavaScript code that hides and later 'should' show again:

function showDropDown() {
    document.getElementById("ssid-dropdown").style.display = 'block';
}

function hideDropDown() {
    document.getElementById("ssid-dropdown").style.display = 'none';
}

Now, the drop-down menu is properly shown as soon as I hover over the main button. But when selecting an item, I call hideDropDown() to hide the menu even if not hovered outside of the items.

I notified that as soon as the hideDropDown() function is called, the following is added in the CSS window of Chrome's debug windows:

element.style {
    display: none;
}

I guess, that is a kind of CSS generated because my JavaScript function call of hideDropDown(). However, as soon as this element.stlye is occuring, the hovering/show of the drop-down menu doesn't work anymore.

Any ideas how to solve this issue?


问:
Return sums even if no data exist in given day
I have a table with amounts only on some days, e.g.:

```<code>[DATE] [AMT]
11/1/2017 $123
11/1/2017 $50
11/3/2017 $123
</code>```

How can I query the data and get:

```<code>11/1/2017 $173
11/2/2017 $0
11/3/2017 $123
</code>```

I tried like:

```<code>SELECT Day([Date]) AS [Day], Nz(Sum(AMT),0) AS [Day Total]
FROM mytable
WHERE Month([Date])=11
GROUP BY Day([Date]);
</code>```

But still it doesn't return 0s for days without data, any ideas?

答:
There are two simple solutions.

Join to a table with all dates in the month, as in Juan's answer.

Use this query by user RedFilter to generate the dates.

Body:
I have a table with amounts only on some days, e.g.:

[DATE] [AMT]
11/1/2017 $123
11/1/2017 $50
11/3/2017 $123

How can I query the data and get:

11/1/2017 $173
11/2/2017 $0
11/3/2017 $123

I tried like:

SELECT Day([Date]) AS [Day], Nz(Sum(AMT),0) AS [Day Total]
FROM mytable
WHERE Month([Date])=11
GROUP BY Day([Date]);

But still it doesn't return 0s for days without data, any ideas?


问:
Updating rows in laravel mysql database
I've set up a database and want to update the column status for each row in my UsersController:

I started with this:

```<code>User::where('id', '=', 1)->update(['status' => $status]);
</code>```

This is working, but I need some loop to change all the rows, something like this:

foreach $id from the table

run some code to change individual $status variable

set individual $status value in the 'status' column in each row:

```<code>User::where('id', '=', $id)->update(['status' => $status])
</code>```

end foreach

So for me its unclear how to go through the table via the foreach. Then save the calculated status from my code to each individual id?

答:
@Serge solution is fine for few records but you should be able to use chuck as @ceejayoz suggested</p>

```<code>User::chunk(100, function ($users) {
    $users->each(function ($user) {
        $user->status = getStatus($user);
        $user->save();
    });
});
</code>```

Title: Updating rows in laravel mysql database

Body:
I've set up a database and want to update the column status for each row in my UsersController:

I started with this:

User::where('id', '=', 1)->update(['status' => $status]);

This is working, but I need some loop to change all the rows, something like this:

foreach $id from the table

run some code to change individual $status variable

set individual $status value in the 'status' column in each row:

User::where('id', '=', $id)->update(['status' => $status])

end foreach

So for me its unclear how to go through the table via the foreach. Then save the calculated status from my code to each individual id?

Body:
@Serge solution is fine for few records but you should be able to use chuck as @ceejayoz suggested

User::chunk(100, function ($users) {
    $users->each(function ($user) {
        $user->status = getStatus($user);
        $user->save();
    });
});


问:
URL rewrite replace + with %20
This worked fine in IIS 6. Now using IIS 7.5 and cannot figure the problem out. Trying to get a bespoke app working, it's a file manager. When attempting to access files with spaces in the files names IIS encodes the URL as files/This+is+a+filename.doc and throws a cannot find file. I need it to encode the URL as files/This%20is%20a%20filename.doc.

Been looking at URL rewrite but cannot get my head around it.

Any ideas?

答: You can change url encoding. No need for regular expressions.</p>

Title: URL rewrite replace + with %20


问:
Restart Spyder IPython console in script
Currently I am doing some debugging on a script but when I run it the second time I get a false outcome. Now I want to restart the IPython console everytime when I run my script e.i. I want to include it in my script and do it automatically. I already tried to clear and restart my console but that doesn’t work. Has somebody an idea how I can solve this problem?

Thank you for your help!

答:
Do you want to clear out all variables from previous run when you re-run the script? If yes, you can change the preference settings in Spyder.

Go to Tools > Preferences > Run > Check the box that says "Clear all variables before execution."


问:
CSS Hover not showing
Okay, so I have an image for a background that has 1px of a blur filter in the CSS.

That works.

Then, I added a CSS :hover selector to a new CSS rule that changes the blur filter to 0.

When I hover over it on the browser, however, it doesn't change the blur at all! (I went into Google Chrome Inspect Element and used the handy feature of forcing the :hover selector, and then it worked. So I know it's not the CSS that's buggy.)

How can I get this to work? It's a blur filter on a div in a header. Any ideas?

```<code>    <header>
        <div id="bgimage"></div>
        <nav>
            <a href="home.html" title="Click to go to the homepage.">Home</a>
            <span class="divider">-</span>
            <a href="cakes.html" title="Click to see types of cakes.">Types of Cake</a>
        </nav>
        <h1>Cakes</h1>
    </header>

body header {
    width:100%;
    text-align:center;
    box-shadow:0 4px 4px 4px rgba(0,0,0,0.2);
    z-index:4;
    position:relative;
    background-color:linear-gradient(CornFlowerBlue,RoyalBlue);
}
body header div#bgimage {
    background-attachment:fixed;
    background-position:center;
    background-size:cover;
    background-image:url(hydrangea-cakes-2.jpg);
    filter:blur(1px);
    position:absolute;
    width:100%;
    height:100%;
}
</code>```

The important parts of the HTML are the header and the div id="bgimage"

答:
You haven't already added the :hover pseudo-class.

#bgimage:hover {
  /* the styles you want to display on hover */
}
```

Title: CSS Hover not showing

Body:
Okay, so I have an image for a background that has 1px of a blur filter in the CSS.

That works.

Then, I added a CSS :hover selector to a new CSS rule that changes the blur filter to 0.

When I hover over it on the browser, however, it doesn't change the blur at all! (I went into Google Chrome Inspect Element and used the handy feature of forcing the :hover selector, and then it worked. So I know it's not the CSS that's buggy.)

How can I get this to work? It's a blur filter on a div in a header. Any ideas?

            Home
            -
            Types of Cake

Cakes

body header {
    width:100%;
    text-align:center;
    box-shadow:0 4px 4px 4px rgba(0,0,0,0.2);
    z-index:4;
    position:relative;
    background-color:linear-gradient(CornFlowerBlue,RoyalBlue);
}
body header div#bgimage {
    background-attachment:fixed;
    background-position:center;
    background-size:cover;
    background-image:url(hydrangea-cakes-2.jpg);
    filter:blur(1px);
    position:absolute;
    width:100%;
    height:100%;
}

The important parts of the HTML are the header and the div id="bgimage"

ContentLicense: CC BY-SA 4.0


问:
datetimeoffset hibernate mapping
I'm trying to use hibernate with ms sql server and have difficulties mapping the sql type datetimeoffset to java.
If I try to set the mapping type in the reverse engineering configuration with:

I get an error saying sth. like
  org.hibernate.MappingException: jdbc-type: microsoft.sql.Types.DATETIMEOFFSET is not a known JDBC Type nor a valid number

I guess only the detault jdbc types can be used in this context.

Any ideas about how to solve this issue?

答:
Your can provide a custom Hibernate user type. For example by implementing org.hibernate.type.MutableType.

Refer Hibernate Reference for more information.

Title: datetimeoffset hibernate mapping


问:
Updated util.scanner repeating method
I have fixed the errors in my original code and formatted it correctly.  However, the code is now repeating String next() before it proceeds to the last method.  I thought I understood why, but when I tried to fix it, the program failed again.  Thank you for your time!</p>

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

public class LearnScanner {
    public static void main (String[] args) {
        first();
        next();
        third();
    }
    public static void first() {
        Scanner input = new Scanner(System.in);
        System.out.println("Welcome to Vacation Planner!!");
        System.out.print("What is your name?");
        String name = input.nextLine();
        System.out.print("Nice to meet you " + name + ", where are you travelling to?");
        String destination = input.nextLine();
        System.out.println("Great! "+destination +" sounds like a great trip");
     }
    public static String next() {
        Scanner input = new Scanner(System.in);
        System.out.print("How many days are you going to spend travelling?");
        String days = input.nextLine();
        System.out.print("How much money in USD are you planning to spend on your trip?");
        String budget = input.nextLine();
        System.out.print("What is the three letter currency symbol for your travel destination?");
        String currency = input.nextLine();
        System.out.print("How many " + currency + " are there in 1 USD?");
        String currencyConversion = input.nextLine();
        return days;
    }
    public static void third() {
        int days = Integer.valueOf(next());
        int hours = days * 24;
        int minutes = hours * 60;
        System.out.println("If your are travelling for " + days + " days that is the same as " + hours + " hours or " + minutes + " minutes");
    }

    }
</code>```

答:
From what I see, the method next() gets called once from the main method, and then gets called again in third at

```<code>int days = Integer.valueOf(next());
</code>```

Maybe you should create an instance variable called days and store the value of next() in it. Then use the value of the variable in the third() method. i.e.

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

public class LearnScanner {
    private static int days = 0;

    public static void main (String[] args) {
        first();
        days = Integer.parseInt(next());
        third();
    }
    public static void first() {
        Scanner input = new Scanner(System.in);
        System.out.println("Welcome to Vacation Planner!!");
        System.out.print("What is your name?");
        String name = input.nextLine();
        System.out.print("Nice to meet you " + name + ", where are you travelling to?");
        String destination = input.nextLine();
        System.out.println("Great! "+destination +" sounds like a great trip");
     }
    public static String next() {
        Scanner input = new Scanner(System.in);
        System.out.print("How many days are you going to spend travelling?");
        String days = input.nextLine();
        System.out.print("How much money in USD are you planning to spend on your trip?");
        String budget = input.nextLine();
        System.out.print("What is the three letter currency symbol for your travel destination?");
        String currency = input.nextLine();
        System.out.print("How many " + currency + " are there in 1 USD?");
        String currencyConversion = input.nextLine();
        return days;
    }
    public static void third() {
        int tempDays = Integer.valueOf(days);
        int hours = days * 24;
        int minutes = hours * 60;
        System.out.println("If your are travelling for " + tempDays + " days that is the same as " + hours + " hours or " + minutes + " minutes");
    }
</code>```

Title: Updated util.scanner repeating method

Body:
I have fixed the errors in my original code and formatted it correctly.  However, the code is now repeating String next() before it proceeds to the last method.  I thought I understood why, but when I tried to fix it, the program failed again.  Thank you for your time!

import java.util.Scanner;

public class LearnScanner {
    public static void main (String[] args) {
        first();
        next();
        third();
    }
    public static void first() {
        Scanner input = new Scanner(System.in);
        System.out.println("Welcome to Vacation Planner!!");
        System.out.print("What is your name?");
        String name = input.nextLine();
        System.out.print("Nice to meet you " + name + ", where are you travelling to?");
        String destination = input.nextLine();
        System.out.println("Great! "+destination +" sounds like a great trip");
     }
    public static String next() {
        Scanner input = new Scanner(System.in);
        System.out.print("How many days are you going to spend travelling?");
        String days = input.nextLine();
        System.out.print("How much money in USD are you planning to spend on your trip?");
        String budget = input.nextLine();
        System.out.print("What is the three letter currency symbol for your travel destination?");
        String currency = input.nextLine();
        System.out.print("How many " + currency + " are there in 1 USD?");
        String currencyConversion = input.nextLine();
        return days;
    }
    public static void third() {
        int days = Integer.valueOf(next());
        int hours = days * 24;
        int minutes = hours * 60;
        System.out.println("If your are travelling for " + days + " days that is the same as " + hours + " hours or " + minutes + " minutes");
    }

    }

Body:
From what I see, the method next() gets called once from the main method, and then gets called again in third at

int days = Integer.valueOf(next());

Maybe you should create an instance variable called days and store the value of next() in it. Then use the value of the variable in the third() method. i.e.

import java.util.Scanner;

public class LearnScanner {
    private static int days = 0;

    public static void main (String[] args) {
        first();
        days = Integer.parseInt(next());
        third();
    }
    public static void first() {
        Scanner input = new Scanner(System.in);
        System.out.println("Welcome to Vacation Planner!!");
        System.out.print("What is your name?");
        String name = input.nextLine();
        System.out.print("Nice to meet you " + name + ", where are you travelling to?");
        String destination = input.nextLine();
        System.out.println("Great! "+destination +" sounds like a great trip");
     }
    public static String next() {
        Scanner input = new Scanner(System.in);
        System.out.print("How many days are you going to spend travelling?");
        String days = input.nextLine();
        System.out.print("How much money in USD are you planning to spend on your trip?");
        String budget = input.nextLine();
        System.out.print("What is the three letter currency symbol for your travel destination?");
        String currency = input.nextLine();
        System.out.print("How many " + currency + " are there in 1 USD?");
        String currencyConversion = input.nextLine();
        return days;
    }
    public static void third() {
        int tempDays = Integer.valueOf(days);
        int hours = days * 24;
        int minutes = hours * 60;
        System.out.println("If your are travelling for " + tempDays + " days that is the same as " + hours + " hours or " + minutes + " minutes");
    }


问:
django admin login suddenly demanding csrf token
I was logging into my django admin console easily a few minutes ago. I must have changed something somewhere that caused this error when logging in as superuser:

Forbidden (403)
CSRF verification failed. Request aborted.

This error caught me off guard as I was logging in all night. Why would I suddenly need a csrf token for admin login? You would think the sign in form already has that. This is my admin.py:

```<code>from django.contrib import admin
from accounts.models import Image, Category, UserProfile

class ImageAdmin(admin.ModelAdmin):
    list_display    = ["__unicode__", "title", "created"]

admin.site.register(Image, GenericImageAdmin)

class CategoryAdmin(admin.ModelAdmin):
    list_display    = ["category"]

admin.site.register(Category, CategoryAdmin)

admin.site.register(UserProfile)
</code>```

答:
This could also happen when you are already logged in into your website hosted on a url different than admin. And then try to login into your admin panel in a new tab.
Try to open the admin panel in a different window.</p>

Body:
I was logging into my django admin console easily a few minutes ago. I must have changed something somewhere that caused this error when logging in as superuser:

Forbidden (403)
CSRF verification failed. Request aborted.

This error caught me off guard as I was logging in all night. Why would I suddenly need a csrf token for admin login? You would think the sign in form already has that. This is my admin.py:

from django.contrib import admin
from accounts.models import Image, Category, UserProfile

class ImageAdmin(admin.ModelAdmin):
    list_display    = ["__unicode__", "title", "created"]

admin.site.register(Image, GenericImageAdmin)

class CategoryAdmin(admin.ModelAdmin):
    list_display    = ["category"]

admin.site.register(Category, CategoryAdmin)

admin.site.register(UserProfile)


问:
Use S3DistCp to copy file from S3 to EMR
I am struggling to find a way to use S3DistCp in my AWS EMR Cluster.

Some old examples which show how to add s3distcp as an EMR step use elastic-mapreduce command which is not used anymore.

Some other sources suggest to use s3-dist-cp command, which is not found in current EMR clusters. Even official documentation (online and EMR developer guide 2016 pdf) present an example like this:

```<code>aws emr add-steps --cluster-id j-3GYXXXXXX9IOK --steps Type=CUSTOM_JAR,Name="S3DistCp step",Jar=/home/hadoop/lib/emr-s3distcp-1.0.jar,Args=["--s3Endpoint,s3-eu-west-1.amazonaws.com","--src,s3://mybucket/logs/j-3GYXXXXXX9IOJ/node/","--dest,hdfs:///output","--srcPattern,.*[azA-Z,]+"]
</code>```

But there is no lib folder in the /home/hadoop path. I found some hadoop libraries in this folder: /usr/lib/hadoop/lib, but I cannot find s3distcp from anywhere.

Then I found that there are some libraries available in some S3 buckets. For example, from this question, I found this path: s3://us-east-1.elasticmapreduce/libs/s3distcp/1.latest/s3distcp.jar. This seemed to be a step in the right direction, as adding a new step to a running EMR cluster from the AWS interface with these parameters started the step (which it didn't with previous attempts) but failed after ~15seconds:

```<code>JAR location: s3://us-east-1.elasticmapreduce/libs/s3distcp/1.latest/s3distcp.jar
Main class: None
Arguments: --s3Endpoint s3-eu-west-1.amazonaws.com --src s3://source-bucket/scripts/ --dest hdfs:///output
Action on failure: Continue
</code>```

This resulted in the following error:

```<code>Exception in thread "main" java.lang.RuntimeException: Unable to retrieve Hadoop configuration for key fs.s3n.awsAccessKeyId
    at com.amazon.external.elasticmapreduce.s3distcp.ConfigurationCredentials.getConfigOrThrow(ConfigurationCredentials.java:29)
    at com.amazon.external.elasticmapreduce.s3distcp.ConfigurationCredentials.<init>(ConfigurationCredentials.java:35)
    at com.amazon.external.elasticmapreduce.s3distcp.S3DistCp.createInputFileListS3(S3DistCp.java:85)
    at com.amazon.external.elasticmapreduce.s3distcp.S3DistCp.createInputFileList(S3DistCp.java:60)
    at com.amazon.external.elasticmapreduce.s3distcp.S3DistCp.run(S3DistCp.java:529)
    at com.amazon.external.elasticmapreduce.s3distcp.S3DistCp.run(S3DistCp.java:216)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:84)
    at com.amazon.external.elasticmapreduce.s3distcp.Main.main(Main.java:12)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.hadoop.util.RunJar.run(RunJar.java:221)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:136)
</code>```

I thought this may have been caused by the incompatibility of my S3 location (same as the endpoint) and the location of the s3distcp script, which was from us-east. I replaced it with eu-west-1 and still got the same error about the authentication.
I have used a similar setup to run my scala scripts (Custom jar type with "command-runner.jar" script with the first argument "spark-submit" to run a spark job and this works, I have not had this problem with the authentication before.

What is the simplest way to copy a file from S3 to an EMR cluster? Either by adding an additional EMR step with AWS SDK (for Go lang) or somehow inside the Scala spark script? Or from the AWS EMR interface, but not from CLI as I need it to be automated.

答:
```<code>aws emr add-steps --profile <> --cluster-id <> --steps Type=CUSTOM_JAR,Name=UPLOAD_JAR_CONFIG,ActionOnFailure=CANCEL_AND_WAIT,Jar=command-runner.jar,Args=[s3-dist-cp,--src,s3a://<>/,--dest,hdfs:///<>/<>/,--srcPattern=.*.*]
</code>```

Thanks for previous answers. I was stuck but was able to build this to use dist-cp to copy to emr from s3

Body:
I am struggling to find a way to use S3DistCp in my AWS EMR Cluster.

Some old examples which show how to add s3distcp as an EMR step use elastic-mapreduce command which is not used anymore.

Some other sources suggest to use s3-dist-cp command, which is not found in current EMR clusters. Even official documentation (online and EMR developer guide 2016 pdf) present an example like this:

aws emr add-steps --cluster-id j-3GYXXXXXX9IOK --steps Type=CUSTOM_JAR,Name="S3DistCp step",Jar=/home/hadoop/lib/emr-s3distcp-1.0.jar,Args=["--s3Endpoint,s3-eu-west-1.amazonaws.com","--src,s3://mybucket/logs/j-3GYXXXXXX9IOJ/node/","--dest,hdfs:///output","--srcPattern,.*[azA-Z,]+"]

But there is no lib folder in the /home/hadoop path. I found some hadoop libraries in this folder: /usr/lib/hadoop/lib, but I cannot find s3distcp from anywhere.

Then I found that there are some libraries available in some S3 buckets. For example, from this question, I found this path: s3://us-east-1.elasticmapreduce/libs/s3distcp/1.latest/s3distcp.jar. This seemed to be a step in the right direction, as adding a new step to a running EMR cluster from the AWS interface with these parameters started the step (which it didn't with previous attempts) but failed after ~15seconds:

JAR location: s3://us-east-1.elasticmapreduce/libs/s3distcp/1.latest/s3distcp.jar
Main class: None
Arguments: --s3Endpoint s3-eu-west-1.amazonaws.com --src s3://source-bucket/scripts/ --dest hdfs:///output
Action on failure: Continue

This resulted in the following error:

Exception in thread "main" java.lang.RuntimeException: Unable to retrieve Hadoop configuration for key fs.s3n.awsAccessKeyId
    at com.amazon.external.elasticmapreduce.s3distcp.ConfigurationCredentials.getConfigOrThrow(ConfigurationCredentials.java:29)
    at com.amazon.external.elasticmapreduce.s3distcp.ConfigurationCredentials.<init>(ConfigurationCredentials.java:35)
    at com.amazon.external.elasticmapreduce.s3distcp.S3DistCp.createInputFileListS3(S3DistCp.java:85)
    at com.amazon.external.elasticmapreduce.s3distcp.S3DistCp.createInputFileList(S3DistCp.java:60)
    at com.amazon.external.elasticmapreduce.s3distcp.S3DistCp.run(S3DistCp.java:529)
    at com.amazon.external.elasticmapreduce.s3distcp.S3DistCp.run(S3DistCp.java:216)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:84)
    at com.amazon.external.elasticmapreduce.s3distcp.Main.main(Main.java:12)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.hadoop.util.RunJar.run(RunJar.java:221)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:136)

I thought this may have been caused by the incompatibility of my S3 location (same as the endpoint) and the location of the s3distcp script, which was from us-east. I replaced it with eu-west-1 and still got the same error about the authentication.
I have used a similar setup to run my scala scripts (Custom jar type with "command-runner.jar" script with the first argument "spark-submit" to run a spark job and this works, I have not had this problem with the authentication before.

What is the simplest way to copy a file from S3 to an EMR cluster? Either by adding an additional EMR step with AWS SDK (for Go lang) or somehow inside the Scala spark script? Or from the AWS EMR interface, but not from CLI as I need it to be automated.

Body:
aws emr add-steps --profile <> --cluster-id <> --steps Type=CUSTOM_JAR,Name=UPLOAD_JAR_CONFIG,ActionOnFailure=CANCEL_AND_WAIT,Jar=command-runner.jar,Args=[s3-dist-cp,--src,s3a://<>/,--dest,hdfs:///<>/<>/,--srcPattern=.*.*]

Thanks for previous answers. I was stuck but was able to build this to use dist-cp to copy to emr from s3


问:
Creating a line graph using ggplot2 without a set "y"?
I guess I am trying to create a geom_line version of a geom_bar.  The reason I want to do lines is because when I enter

```<code>geom_bar(aes(fill = Decile), position = position_dodge())
</code>```

I am stuck with ten segments and my bar chart looks extremely cluttered.
  I have 11 separate x variables going across the bottom.
The problem is I dont know how to use the count as a "y" variable and have tried things like ..count.. and other approached but am completely lost. Any ideas?

Thanks for the help!

My data looks like this:

Name Decile Division

Joe 1 San Diego

Jan 1 New York

Jay 2 San Diego

Lue 3 Dallas

Suz 2 Seattle

tye 3 Dallas

```<code>MCD <- read.csv("Decile15.csv", header = TRUE)

MCD$MonthNo <- factor(MCD$MonthNo, levels = c(1:11), labels = c("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November"))

Decile_names <- c('1' = "Decile #1",
                '2' = "Decile #2",
                '3' = "Decile #3",
                '4' = "Decile #4",
                '5' = "Decile #5"
                 )

MCDGraph <- ggplot(na.omit(MCD), aes(MonthNo))

MCDGraph + geom_bar(aes(fill = Division), color = "black", position = "fill") +     facet_wrap(~Decile, nrow = 1, labeller = labeller(Decile = as_labeller(Decile_names))) + theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5)) +     scale_fill_manual(values = c("#DA4424", "#24A0DA", "#F0BC0B", "#43F749", "#4348F7", "#F74369", "#D7B9F5")) + theme(panel.background = element_rect(colour = "black", fill = "white"), panel.grid.minor = element_line(color = "black", size = .5)) + labs(x = "2017", y = "% of Leads Per Month By Division") + scale_y_continuous(labels = percent_format()) + theme(strip.background = element_blank(), strip.text = element_text(size = 25))
</code>```

This is what my % of grouped facet_wrap bar chart looked like.

I split those into 5 so that I could see five plots instead of 10 on one pdf sheet.  Also this is only divided into the 7 total divisions.  I want to do one that is divided into 10.  Here is an example I used to make my grouped regular without faceting anything.

```<code>MC <- read.csv("2017_Full_year.csv", header = TRUE)

MC$MonthNo <- factor(MC$MonthNo, levels = c(1:11), labels = c("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November"))

MCH <- ggplot(na.omit(MC), aes(MonthNo))

MCH + geom_bar(aes(fill = Division), position = position_dodge() ) + labs(x = "2017", y = "# of Leads") + theme(axis.line = element_line(color = "black", size = 3, linetype = "solid"), axis.text.x = element_text(face = "bold", color = "black", size = 14),
  axis.text.y = element_text(face = "bold", color = "black", size = 14)) + scale_y_continuous(name = "# Of Leads", breaks = seq(0,1000, 50)) + theme(panel.background = element_rect(colour = "black",
  fill = "white"), panel.grid.minor = element_line(color = "black", size = .5), panel.grid.major = element_line(color = "black", size = .5)) +
  scale_fill_manual(values = c("#DA4424", "#24A0DA", "#F0BC0B", "#43F749", "#4348F7", "#F74369","#D7B9F5"))
</code>```

EDIT: Or should I just create a new csv with the the final counts for each Decile during each month already in it. This would be a quick fix and I can pull the numbers very easily from SQL server.  I was just hoping to do this without having to create a new file.

答:
This should get you the "geom_line version of geom_bar"

```<code>df <- data.frame(x=c(1,1,1, 3,3, 10,10,10,10))
ggplot(df, aes(x=x)) + geom_line(stat="count")
</code>```

UPDATE:
Here is the version based on the dataset from TBT8's answer

```<code>library(dplyr)
library(ggplot2)

set.seed(99)
#create dummy dataset
MCD <- tibble(
Name = sample(c("Joe", "Jay", "Susan", "Nancy", "Mark"), 1000, T),
Decile = sample(1:10,1000, T) ,
Division = sample(c('San Diego', 'New York', 'Dallas', 'Seattle', 'LA'), 1000, T),
MonthNo = sample(1:11, 1000 , T))

MCD$MonthNo <- factor(MCD$MonthNo, levels = c(1:11),
labels = c("January", "February",
"March", "April", "May",
"June", "July", "August",
"September", "October", "November"))

#create a numeric months vector
MonthNum <- 1:11
names(MonthNum) <- levels(MCD$MonthNo)

#create a factor to be used for facets
MCD$DecileF <- factor(
  MCD$Decile,
  levels=as.character(sort(unique(MCD$Decile),
                           decreasing = TRUE)))

ggplot(MCD, aes(x = MonthNum[MonthNo], col=DecileF)) +
  geom_path(stat = "count") +
  #geom_point(stat = "count") +
  facet_grid(DecileF~.) +
  scale_x_discrete(name ="Month", limits=names(MonthNum))
</code>```

Body:
I guess I am trying to create a geom_line version of a geom_bar.  The reason I want to do lines is because when I enter

geom_bar(aes(fill = Decile), position = position_dodge())

I am stuck with ten segments and my bar chart looks extremely cluttered.
  I have 11 separate x variables going across the bottom.
The problem is I dont know how to use the count as a "y" variable and have tried things like ..count.. and other approached but am completely lost. Any ideas?

Thanks for the help!

My data looks like this:

Name Decile Division

Joe 1 San Diego

Jan 1 New York

Jay 2 San Diego

Lue 3 Dallas

Suz 2 Seattle

tye 3 Dallas

MCD <- read.csv("Decile15.csv", header = TRUE)

MCD$MonthNo <- factor(MCD$MonthNo, levels = c(1:11), labels = c("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November"))

Decile_names <- c('1' = "Decile #1",
                '2' = "Decile #2",
                '3' = "Decile #3",
                '4' = "Decile #4",
                '5' = "Decile #5"
                 )

MCDGraph <- ggplot(na.omit(MCD), aes(MonthNo))

MCDGraph + geom_bar(aes(fill = Division), color = "black", position = "fill") +     facet_wrap(~Decile, nrow = 1, labeller = labeller(Decile = as_labeller(Decile_names))) + theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5)) +     scale_fill_manual(values = c("#DA4424", "#24A0DA", "#F0BC0B", "#43F749", "#4348F7", "#F74369", "#D7B9F5")) + theme(panel.background = element_rect(colour = "black", fill = "white"), panel.grid.minor = element_line(color = "black", size = .5)) + labs(x = "2017", y = "% of Leads Per Month By Division") + scale_y_continuous(labels = percent_format()) + theme(strip.background = element_blank(), strip.text = element_text(size = 25))

This is what my % of grouped facet_wrap bar chart looked like.

I split those into 5 so that I could see five plots instead of 10 on one pdf sheet.  Also this is only divided into the 7 total divisions.  I want to do one that is divided into 10.  Here is an example I used to make my grouped regular without faceting anything.

MC <- read.csv("2017_Full_year.csv", header = TRUE)

MC$MonthNo <- factor(MC$MonthNo, levels = c(1:11), labels = c("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November"))

MCH <- ggplot(na.omit(MC), aes(MonthNo))

MCH + geom_bar(aes(fill = Division), position = position_dodge() ) + labs(x = "2017", y = "# of Leads") + theme(axis.line = element_line(color = "black", size = 3, linetype = "solid"), axis.text.x = element_text(face = "bold", color = "black", size = 14),
  axis.text.y = element_text(face = "bold", color = "black", size = 14)) + scale_y_continuous(name = "# Of Leads", breaks = seq(0,1000, 50)) + theme(panel.background = element_rect(colour = "black",
  fill = "white"), panel.grid.minor = element_line(color = "black", size = .5), panel.grid.major = element_line(color = "black", size = .5)) +
  scale_fill_manual(values = c("#DA4424", "#24A0DA", "#F0BC0B", "#43F749", "#4348F7", "#F74369","#D7B9F5"))

EDIT: Or should I just create a new csv with the the final counts for each Decile during each month already in it. This would be a quick fix and I can pull the numbers very easily from SQL server.  I was just hoping to do this without having to create a new file.

Body:
This should get you the "geom_line version of geom_bar"

df <- data.frame(x=c(1,1,1, 3,3, 10,10,10,10))
ggplot(df, aes(x=x)) + geom_line(stat="count")

UPDATE:
Here is the version based on the dataset from TBT8's answer

library(dplyr)
library(ggplot2)

set.seed(99)
#create dummy dataset
MCD <- tibble(
Name = sample(c("Joe", "Jay", "Susan", "Nancy", "Mark"), 1000, T),
Decile = sample(1:10,1000, T) ,
Division = sample(c('San Diego', 'New York', 'Dallas', 'Seattle', 'LA'), 1000, T),
MonthNo = sample(1:11, 1000 , T))

MCD$MonthNo <- factor(MCD$MonthNo, levels = c(1:11),
labels = c("January", "February",
"March", "April", "May",
"June", "July", "August",
"September", "October", "November"))

#create a numeric months vector
MonthNum <- 1:11
names(MonthNum) <- levels(MCD$MonthNo)

#create a factor to be used for facets
MCD$DecileF <- factor(
  MCD$Decile,
  levels=as.character(sort(unique(MCD$Decile),
                           decreasing = TRUE)))

ggplot(MCD, aes(x = MonthNum[MonthNo], col=DecileF)) +
  geom_path(stat = "count") +
  #geom_point(stat = "count") +
  facet_grid(DecileF~.) +
  scale_x_discrete(name ="Month", limits=names(MonthNum))


问:
How to select all options in select2 JavaScript multiselect
The other day, I was trying to figure out how to select all items in select2 v3.5.1 JavaScript multiselect control. I tried a few things, but I was having a difficult time figuring out how to do it. I just wanted to select every option in the box, but apparently select2 does not have a built-in option to select all of the items for you.</p>

答:
Based on the discussion here: https://github.com/select2/select2/issues/195 it is possible to add a Select All button inside the dropdown list of options. Per that discussion, selecting too many at once can freeze the browser. Here I have added a functionality to disable the select all button if there are more that 25 options listed:

https://jsfiddle.net/hula_zell/50v60cm6/


问:
Use 100% div width, if 50% width is too small
How could one go about creating a div, that would have a default size of XX%, however, if the screen gets too small it would switch into 100% size? I have tried using min-width property but the problem with this is that it will not be responsive after the min-width is reached and will overflow if the screen is even smaller.

答:
You have to use @media queries. So let's say you have a
 that should take up only 50% of the web page and then you need to show it full width once it enters mobile phone, say 640px width:

div {
  width: 50%;
}

@media screen and (max-width: 640px) {
  div {
    width: 100%;
  }
}
```

Body:
You have to use @media queries. So let's say you have a <div> that should take up only 50% of the web page and then you need to show it full width once it enters mobile phone, say 640px width:

div {
  width: 50%;
}

@media screen and (max-width: 640px) {
  div {
    width: 100%;
  }
}


问:
How to fix Fortran runtime error: End of file?
I am trying to read a file called "syerasg.txt" in Fortran90. This text file includes panel data on 91 variables (columns) for 8984 individuals for 16 years (143 744 rows). This variables are divided in 7 groups and this groups are divided in 13 subgroups. I am trying to read this file with the following code:

```<code> PROGRAM main
    IMPLICIT NONE

    INTEGER, PARAMETER :: p=8984, tf=16, sem=53, emp=7, gap=13
    INTEGER :: r, t, j, m, g, x, i, IOstatus
    INTEGER, DIMENSION (p,tf,emp) :: yemp
    INTEGER, DIMENSION (p,tf,emp,gap) :: gaps
    OPEN(UNIT=4, FILE='syearsg.txt',STATUS='old') !start gap years
DO i=1,p
    DO t=1,tf
        DO j=1,emp
            IF (j==1) THEN
                READ(4,*)(gaps(i,t,j,g),g=1,13)
            ELSE IF (j==2) THEN
                READ(4,*)(gaps(i,t,j,g-13),g=14,26)
            ELSE IF (j==3) THEN
                READ(4,*)(gaps(i,t,j,g-26),g=27,39)
            ELSE IF (j==4) THEN
                READ(4,*)(gaps(i,t,j,g-39),g=40,52)
            ELSE IF (j==5) THEN
                READ(4,*)(gaps(i,t,j,g-52),g=53,65)
            ELSE IF (j==6) THEN
                READ(4,*)(gaps(i,t,j,g-65),g=66,78)
            ELSE IF (j==7) THEN
                READ(4,*)(gaps(i,t,j,g-78),g=79,91)
            END IF
        END DO
   END DO
END DO
CLOSE(4)
END PROGRAM main
</code>```

When, running the code I get the following message:

Fortran runtime error: End of file

Any ideas on how to solve this?

答:
Your loop nest issues 1,006,208 (that is p*tf*emp) read statements.  It's no surprise that the program runs past the end of a file with only 143,744 lines.  read reads the values it is asked to read, then skips to the start of the next line ready for the next read.

You might be able to fix your program by fiddling around with non-advancing input, ie telling the read statements not to skip to the start of the next line.  But it would be easier not to.

From what you write you should only be issuing p*tf read statements, then reading a single line containing 91 elements, then distributing those elements into gaps as your logic demands.

You might revise your code to something like this (untested and not very carefully checked)

```<code>INTEGER, DIMENSION(91) :: workvec
...
DO i=1,p
    DO t=1,tf
       READ(4,*) workvec
       gaps(i,t,1,1:13) = workvec( 1:13)
       gaps(i,t,2,1:13) = workvec(14:26)
       ...
    END DO
END DO
</code>```

Body:
I am trying to read a file called "syerasg.txt" in Fortran90. This text file includes panel data on 91 variables (columns) for 8984 individuals for 16 years (143 744 rows). This variables are divided in 7 groups and this groups are divided in 13 subgroups. I am trying to read this file with the following code:

 PROGRAM main
    IMPLICIT NONE

    INTEGER, PARAMETER :: p=8984, tf=16, sem=53, emp=7, gap=13
    INTEGER :: r, t, j, m, g, x, i, IOstatus
    INTEGER, DIMENSION (p,tf,emp) :: yemp
    INTEGER, DIMENSION (p,tf,emp,gap) :: gaps
    OPEN(UNIT=4, FILE='syearsg.txt',STATUS='old') !start gap years
DO i=1,p
    DO t=1,tf
        DO j=1,emp
            IF (j==1) THEN
                READ(4,*)(gaps(i,t,j,g),g=1,13)
            ELSE IF (j==2) THEN
                READ(4,*)(gaps(i,t,j,g-13),g=14,26)
            ELSE IF (j==3) THEN
                READ(4,*)(gaps(i,t,j,g-26),g=27,39)
            ELSE IF (j==4) THEN
                READ(4,*)(gaps(i,t,j,g-39),g=40,52)
            ELSE IF (j==5) THEN
                READ(4,*)(gaps(i,t,j,g-52),g=53,65)
            ELSE IF (j==6) THEN
                READ(4,*)(gaps(i,t,j,g-65),g=66,78)
            ELSE IF (j==7) THEN
                READ(4,*)(gaps(i,t,j,g-78),g=79,91)
            END IF
        END DO
   END DO
END DO
CLOSE(4)
END PROGRAM main

When, running the code I get the following message:

Fortran runtime error: End of file

Any ideas on how to solve this?

Body:
Your loop nest issues 1,006,208 (that is p*tf*emp) read statements.  It's no surprise that the program runs past the end of a file with only 143,744 lines.  read reads the values it is asked to read, then skips to the start of the next line ready for the next read.

You might be able to fix your program by fiddling around with non-advancing input, ie telling the read statements not to skip to the start of the next line.  But it would be easier not to.

From what you write you should only be issuing p*tf read statements, then reading a single line containing 91 elements, then distributing those elements into gaps as your logic demands.

You might revise your code to something like this (untested and not very carefully checked)

INTEGER, DIMENSION(91) :: workvec
...
DO i=1,p
    DO t=1,tf
       READ(4,*) workvec
       gaps(i,t,1,1:13) = workvec( 1:13)
       gaps(i,t,2,1:13) = workvec(14:26)
       ...
    END DO
END DO


问:
Get AWS device farm test video URL link in to my test management tool (Practitest)
I am working on appium java TestNG with maven and I run the script on device farm.Device farm generates 3 o/p in the form of logs, videos, and screenshot. My target is to get videos URL into practitest. This is my test management tool. So my question is how can I get videos URL link of Device farm test videos?</p>

答:
Here is a short python script that gets all the videos, creates a directory in the current working directory, then puts all the videos in that directory. I made this when using winders so you'll need to change the file path for a mac.

To use it first get the project arn by doing:

```<code>aws devicefarm list-projects --region us-west-2
</code>```

Then once we have a project arn open a cmn window, cd to the directory this code is in and type:

```<code>python somefilename.py --project-arn  arn:aws:devicefarm:us-west-2:accountNUm:project:11111111-2222-3333-4444-555555555555
</code>```

and it should start downloading each video

```<code>import boto3
import json
import requests
import time
import argparse
import sys
import os
import errno

#Device Farm is only available in us-west-2
client = boto3.client('devicefarm',region_name='us-west-2')
# Read in command-line parameters
parser = argparse.ArgumentParser()
#get the project, test, and run types
parser.add_argument("--project-arn", action="store", required=True, dest="projectarn", help="aws devicefarm list-projects --region us-west-2")

args = parser.parse_args()

#list the runs
#https://boto3.readthedocs.io/en/latest/reference/services/devicefarm.html#DeviceFarm.Client.list_runs
runs = client.list_runs(arn=args.projectarn)

for run in runs['runs']:
    index = 0
    #list the artifacts and get the videos
    #https://boto3.readthedocs.io/en/latest/reference/services/devicefarm.html#DeviceFarm.Client.list_artifacts
    artifacts = client.list_artifacts(
        arn=run['arn'],
        type='FILE'
    )
    #print(json.dumps(artifacts))
    for artifact in artifacts['artifacts']:
        #get videos
        video_url = ''
        if artifact['type'] == "VIDEO":
            print (str(artifact) + "\n")
            video_url =  artifact['url']
            response = requests.request("GET", video_url)
            cwd = os.getcwd()
            filename = cwd + "\\videos\\" + "video" + str(index) + ".mp4"
            print (filename + "\n")
            if not os.path.exists(os.path.dirname(filename)):
                try:
                    print("trying to create directory")
                    os.makedirs(os.path.dirname(filename))
                except OSError as exc: # Guard against race condition
                    if exc.errno != errno.EEXIST:
                        raise
            with open(filename, "wb") as f:
                print("writing response to file")
                f.write(response.content)
                f.close()
                index = index + 1
</code>```

Body:
Here is a short python script that gets all the videos, creates a directory in the current working directory, then puts all the videos in that directory. I made this when using winders so you'll need to change the file path for a mac.

To use it first get the project arn by doing:

aws devicefarm list-projects --region us-west-2

Then once we have a project arn open a cmn window, cd to the directory this code is in and type:

python somefilename.py --project-arn  arn:aws:devicefarm:us-west-2:accountNUm:project:11111111-2222-3333-4444-555555555555

and it should start downloading each video

import boto3
import json
import requests
import time
import argparse
import sys
import os
import errno

#Device Farm is only available in us-west-2
client = boto3.client('devicefarm',region_name='us-west-2')
# Read in command-line parameters
parser = argparse.ArgumentParser()
#get the project, test, and run types
parser.add_argument("--project-arn", action="store", required=True, dest="projectarn", help="aws devicefarm list-projects --region us-west-2")

args = parser.parse_args()

#list the runs
#https://boto3.readthedocs.io/en/latest/reference/services/devicefarm.html#DeviceFarm.Client.list_runs
runs = client.list_runs(arn=args.projectarn)

for run in runs['runs']:
    index = 0
    #list the artifacts and get the videos
    #https://boto3.readthedocs.io/en/latest/reference/services/devicefarm.html#DeviceFarm.Client.list_artifacts
    artifacts = client.list_artifacts(
        arn=run['arn'],
        type='FILE'
    )
    #print(json.dumps(artifacts))
    for artifact in artifacts['artifacts']:
        #get videos
        video_url = ''
        if artifact['type'] == "VIDEO":
            print (str(artifact) + "\n")
            video_url =  artifact['url']
            response = requests.request("GET", video_url)
            cwd = os.getcwd()
            filename = cwd + "\\videos\\" + "video" + str(index) + ".mp4"
            print (filename + "\n")
            if not os.path.exists(os.path.dirname(filename)):
                try:
                    print("trying to create directory")
                    os.makedirs(os.path.dirname(filename))
                except OSError as exc: # Guard against race condition
                    if exc.errno != errno.EEXIST:
                        raise
            with open(filename, "wb") as f:
                print("writing response to file")
                f.write(response.content)
                f.close()
                index = index + 1


问:
Python Flask Login (Validate Issues)
Hi I am having trouble getting my login to work. I have set up a database and done login page with a form. I added a username and password to the database but the page seems to still not be logging in.

I think something to do with the Validate. It keeps saying 'Invalid Credentials. Please try again.'even though the username and password are correct.

```<code>    completion = validate(username, password)
    if completion == False:
        error = 'Invalid Credentials. Please try again.'
    else:
        return redirect(url_for('dashboard'))
</code>```

Thanks in Advance:)

I new to Python and Flask. P.S. I cant use any other libraries e.g sqlalchemy

index.py

```<code>from flask import Flask, render_template, redirect, url_for, request, g
import sqlite3
import hashlib

app = Flask(__name__)

# To convert the user input password as MD5
def check_password(hashed_password, user_password):
    return hashed_password == hashlib.md5(user_password.encode()).hexdigest()

# Takes the inputed username and passwords as arguments, and compare them against the users table
def validate(username, password):
    con = sqlite3.connect('var/data.db')
    completion = False
    with con:
                cur = con.cursor()
                cur.execute("SELECT * FROM Users")
                rows = cur.fetchall()
                for row in rows:
                    dbUser = row[1]
                    dbPass = row[2]
                    if dbUser == username:
                        completion = check_password(dbPass, password)
    return completion

def init_db():
    with app.app_context():
        con = sqlite3.connect('var/data.db')
        with app.open_resource('var/schema.sql', mode='r') as f:
            con.cursor().executescript(f.read())
        con.commit()

#The Homepage Route
@app.route("/")
def index():
  return render_template('index.html', title='Home')

#The Login Route
@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        completion = validate(username, password)
        if completion == False:
            error = 'Invalid Credentials. Please try again.'
        else:
            return redirect(url_for('dashboard'))
    return render_template('login.html', error=error)

#The Dashboard Route
@app.route('/dashboard')
def dashboard():
    #return "You have successfully logged in"
    return render_template('dashboard.html', title='Dashboard')

#The Adds to the List
@app.route('/add', methods=['GET','POST'])
def add():
  if not session.get('username'):
      abort(401)
  db = get_db()
  db.execute('INSERT INTO Bucketlist (title,day,desc) VALUES(?,?,?)',
            [request.form['title'], request.form['day'], request.form['desc']])
  db.commit()
  flash('Your wish has been added to your list')
  return redirect(url_for('dashboard'))

#The Removes from the List
@app.route('/remove', methods=['GET'])
def remove():
  delete = request.args.get('bucket_id', '')
  print delete
  db = get_db()
  db.execute('DELETE FROM Bucketlist WHERE title=?', [delete])
  db.commit()
  cur = db.execute("select * from Bucketlist")
  row = cur.fetchall()
  flash('Your wish has been removed from your list')
  return render_template("dashboard.html",row=row)

#Logs Out The User from Their Account
@app.route('/logout')
def logout():
  session.pop('username', None)
  flash('You Have Successful Loged Out')
  return redirect(url_for('index'))

if __name__ == "__main__":
  app.run(host='0.0.0.0', debug=True)
</code>```

login.html

```<code>{% extends "base.html" %}
{% block content %}

  <div class="container">
    <h1>Sign In to View Your WounderList</h1>
      <h2 class="form-text">Create Your Account Here!</h2>
<form action="/login" method="post">
        <input type="text" placeholder="Username" name="username" value="{{
          request.form.username }}">
         <input type="password" placeholder="Password" name="password" value="{{
          request.form.password }}">
        <input class="btn btn-default" type="submit" value="Login">
      </form>
      {% if error %}
        <p class="error"><strong>Error:</strong> {{ error }}
      {% endif %}
  </div>

{% endblock %}
</code>```

schema.sql

```<code>DROP TABLE if EXISTS Users;
DROP TABLE if EXISTS Bucketlist;

CREATE TABLE Users (
    user_id INTEGER PRIMARY KEY,
    username    VARCHAR(16) NOT NULL UNIQUE,
    password    VARCHAR(16) NOT NULL
);

CREATE TABLE Bucketlist (
    bucket_id INTEGER NOT NULL,
    title VARCHAR(32) NOT NULL,
    day DATE NOT NULL,
    desc VARCHAR(256) NOT NULL,
    user_id INTEGER,
    PRIMARY KEY (bucket_id),
    FOREIGN KEY (user_id) REFERENCES users(user_id)
);
</code>```

答:
First you should know that you are not really making a "login", you are just checking a password. A login requires managing a session after the user logs in and the password is accepted.

I suspect the issue is with your password hashing so for testing purposes you should try your code without the hash. See if you can validate a plain text password first.

Secondly, it is a much better idea to just use a Flask library made for this specific purpose like Flask-Login, but I suppose you are a student or something.

Title: Python Flask Login (Validate Issues)

Body:
Hi I am having trouble getting my login to work. I have set up a database and done login page with a form. I added a username and password to the database but the page seems to still not be logging in.

I think something to do with the Validate. It keeps saying 'Invalid Credentials. Please try again.'even though the username and password are correct.

    completion = validate(username, password)
    if completion == False:
        error = 'Invalid Credentials. Please try again.'
    else:
        return redirect(url_for('dashboard'))

Thanks in Advance:)

I new to Python and Flask. P.S. I cant use any other libraries e.g sqlalchemy

index.py

from flask import Flask, render_template, redirect, url_for, request, g
import sqlite3
import hashlib

app = Flask(__name__)

# To convert the user input password as MD5
def check_password(hashed_password, user_password):
    return hashed_password == hashlib.md5(user_password.encode()).hexdigest()

# Takes the inputed username and passwords as arguments, and compare them against the users table
def validate(username, password):
    con = sqlite3.connect('var/data.db')
    completion = False
    with con:
                cur = con.cursor()
                cur.execute("SELECT * FROM Users")
                rows = cur.fetchall()
                for row in rows:
                    dbUser = row[1]
                    dbPass = row[2]
                    if dbUser == username:
                        completion = check_password(dbPass, password)
    return completion

def init_db():
    with app.app_context():
        con = sqlite3.connect('var/data.db')
        with app.open_resource('var/schema.sql', mode='r') as f:
            con.cursor().executescript(f.read())
        con.commit()

#The Homepage Route
@app.route("/")
def index():
  return render_template('index.html', title='Home')

#The Login Route
@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        completion = validate(username, password)
        if completion == False:
            error = 'Invalid Credentials. Please try again.'
        else:
            return redirect(url_for('dashboard'))
    return render_template('login.html', error=error)

#The Dashboard Route
@app.route('/dashboard')
def dashboard():
    #return "You have successfully logged in"
    return render_template('dashboard.html', title='Dashboard')

#The Adds to the List
@app.route('/add', methods=['GET','POST'])
def add():
  if not session.get('username'):
      abort(401)
  db = get_db()
  db.execute('INSERT INTO Bucketlist (title,day,desc) VALUES(?,?,?)',
            [request.form['title'], request.form['day'], request.form['desc']])
  db.commit()
  flash('Your wish has been added to your list')
  return redirect(url_for('dashboard'))

#The Removes from the List
@app.route('/remove', methods=['GET'])
def remove():
  delete = request.args.get('bucket_id', '')
  print delete
  db = get_db()
  db.execute('DELETE FROM Bucketlist WHERE title=?', [delete])
  db.commit()
  cur = db.execute("select * from Bucketlist")
  row = cur.fetchall()
  flash('Your wish has been removed from your list')
  return render_template("dashboard.html",row=row)

#Logs Out The User from Their Account
@app.route('/logout')
def logout():
  session.pop('username', None)
  flash('You Have Successful Loged Out')
  return redirect(url_for('index'))

if __name__ == "__main__":
  app.run(host='0.0.0.0', debug=True)

login.html

{% extends "base.html" %}
{% block content %}

Sign In to View Your WounderList

Create Your Account Here!

<form action="/login" method="post">
        <input type="text" placeholder="Username" name="username" value="{{
          request.form.username }}">
         <input type="password" placeholder="Password" name="password" value="{{
          request.form.password }}">
        <input class="btn btn-default" type="submit" value="Login">
      </form>
      {% if error %}

Error: {{ error }}
      {% endif %}

{% endblock %}

schema.sql

DROP TABLE if EXISTS Users;
DROP TABLE if EXISTS Bucketlist;

CREATE TABLE Users (
    user_id INTEGER PRIMARY KEY,
    username    VARCHAR(16) NOT NULL UNIQUE,
    password    VARCHAR(16) NOT NULL
);

CREATE TABLE Bucketlist (
    bucket_id INTEGER NOT NULL,
    title VARCHAR(32) NOT NULL,
    day DATE NOT NULL,
    desc VARCHAR(256) NOT NULL,
    user_id INTEGER,
    PRIMARY KEY (bucket_id),
    FOREIGN KEY (user_id) REFERENCES users(user_id)
);