问:
Background color does not cover entire -element when hovered
I am currently coding a navigation bar where when the links are hovered, the background-color of the -element changes. Currently, the background-color in the navigation bar's dropdown menu does not cover the entire "box".

body {
  margin: 0;
  font-family: Arial, Helvetica, sans-serif;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  background-color: black;
}

ul li {
  display: inline-block;
  position: relative;
  background-color: black;
}

ul li a {
  display: block;
  color: white;
  text-decoration: none;
  text-align: center;
  margin: -left:0;
  padding: 15px 25px;
  -webkit-transition-duration: 0.4s;
  transition-duration: 0.4s;
}

ul li a:hover {
  background-color: #333;
}

ul li ul#dropdowncontent {
  display: inline-block;
  position: absolute;
  text-align: center;
  min-width: 100%;
  font-size: 70%;
  z-index: 999;
  width: 90px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>Produkter
    <ul id="dropdowncontent">
      <li>Moderkort</li>
      <li>Processorer</li>
      <li>Hårddiskar</li>
      <li>Grafikkort</li>
    </ul>
  </li>
  <li>Butiker</li>
  <li>Kontakt</li>
  <li>Vanliga frågor</li>
</ul></code>```

You can also take a look at the code in this Jsfiddle: https://jsfiddle.net/fdvcmnx6/

答:
set your dropdown list width:100%

```<code>#dropdowncontent li {
    display: block;
}
</code>```

Title: Background color does not cover entire <a>-element when hovered

Body:
I am currently coding a navigation bar where when the links are hovered, the background-color of the -element changes. Currently, the background-color in the navigation bar's dropdown menu does not cover the entire "box".

body {
  margin: 0;
  font-family: Arial, Helvetica, sans-serif;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  background-color: black;
}

ul li {
  display: inline-block;
  position: relative;
  background-color: black;
}

ul li a {
  display: block;
  color: white;
  text-decoration: none;
  text-align: center;
  margin: -left:0;
  padding: 15px 25px;
  -webkit-transition-duration: 0.4s;
  transition-duration: 0.4s;
}

ul li a:hover {
  background-color: #333;
}

ul li ul#dropdowncontent {
  display: inline-block;
  position: absolute;
  text-align: center;
  min-width: 100%;
  font-size: 70%;
  z-index: 999;
  width: 90px;
}

Produkter

Moderkort

Processorer

Hårddiskar

Grafikkort

Butiker

Kontakt

Vanliga frågor

You can also take a look at the code in this Jsfiddle: https://jsfiddle.net/fdvcmnx6/

Body:
set your dropdown list width:100%

#dropdowncontent li {
    display: block;
}


来源: stackexchange

问:
How to set callback function on submit button in bootstrap?
I use bootstrap modal dialog as the user register form as below:

```<code><form>
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3 class="modal-title" id="signupModalLabel">Sign Up</h3>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="user-name-input">User Name</label>
                            <input type="text" class="form-control" id="user-name-input" placeholder="User Name" required>
                        </div>
                        <div class="form-group">
                            <label for="user-email-input">Email address</label>
                            <input type="email" class="form-control" id="user-email-input" aria-describedby="emailHelp" placeholder="Enter email" required>
                        </div>
                        <div class="form-group">
                            <label for="userPasswordInput">Password</label>
                            <input type="password" class="form-control" id="user-password-input" placeholder="Password">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="submit" id="signup-submit-button" class="btn btn-primary">Submit</button>
                    </div>
                </div>
            </div>
        </form>
</code>```

it works fine and I want to add callback function for the submit button. I need to call a web socket request on that callback. If I do it as below:

```<code>$("#signup-submit-button").click(signup);

const signup = () => {
    // make a web socket call
}
</code>```

the callback function signup can be called but all form input validations don't work. Each input in the form has a required attribute. If I leave this blank bootstrap validation should be triggered to validate the form value.

How can I add a callback after pass validation check?

答:
This seems working fine for me

$("#signup-submit-button").click(signup);

var signup = () => {
    // make a web socket call
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta.2/css/bootstrap-grid.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3 class="modal-title" id="signupModalLabel">Sign Up</h3>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="user-name-input">User Name</label>
                            <input type="text" class="form-control" id="user-name-input" placeholder="User Name" required>
                        </div>
                        <div class="form-group">
                            <label for="user-email-input">Email address</label>
                            <input type="email" class="form-control" id="user-email-input" aria-describedby="emailHelp" placeholder="Enter email" required>
                        </div>
                        <div class="form-group">
                            <label for="userPasswordInput">Password</label>
                            <input type="password" class="form-control" id="user-password-input" placeholder="Password">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="submit" id="signup-submit-button" class="btn btn-primary">Submit</button>
                    </div>
                </div>
            </div>
        </form></code>```

ContentLicense: CC BY-SA 3.0

Body:
I use bootstrap modal dialog as the user register form as below:

<form>

Sign Up

                            User Name
                            <input type="text" class="form-control" id="user-name-input" placeholder="User Name" required>

                            Email address
                            <input type="email" class="form-control" id="user-email-input" aria-describedby="emailHelp" placeholder="Enter email" required>

                            Password
                            <input type="password" class="form-control" id="user-password-input" placeholder="Password">

                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="submit" id="signup-submit-button" class="btn btn-primary">Submit</button>

        </form>

it works fine and I want to add callback function for the submit button. I need to call a web socket request on that callback. If I do it as below:

$("#signup-submit-button").click(signup);

const signup = () => {
    // make a web socket call
}

the callback function signup can be called but all form input validations don't work. Each input in the form has a required attribute. If I leave this blank bootstrap validation should be triggered to validate the form value.

How can I add a callback after pass validation check?

Body:
This seems working fine for me

$("#signup-submit-button").click(signup);

var signup = () => {
    // make a web socket call
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta.2/css/bootstrap-grid.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3 class="modal-title" id="signupModalLabel">Sign Up</h3>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="user-name-input">User Name</label>
                            <input type="text" class="form-control" id="user-name-input" placeholder="User Name" required>
                        </div>
                        <div class="form-group">
                            <label for="user-email-input">Email address</label>
                            <input type="email" class="form-control" id="user-email-input" aria-describedby="emailHelp" placeholder="Enter email" required>
                        </div>
                        <div class="form-group">
                            <label for="userPasswordInput">Password</label>
                            <input type="password" class="form-control" id="user-password-input" placeholder="Password">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="submit" id="signup-submit-button" class="btn btn-primary">Submit</button>
                    </div>
                </div>
            </div>
        </form>


问:
Limit the string length of TextBox when it is updated with Binding
I know that you can limit the input characters of TextBox from user by setting MaxLength property.

Is there a similar way to limit the number of characters shown in Text when the Text is updated with Binding? For example, when it is updated from Binding just show the first 5 characters and leave the rest?

Update:
Thanks for all the info, I got inspired by your recommendation and in the end did it with a converter. Here is how I did it, if someone wants to use it later.

```<code>    public class StringLimiter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string val = value.ToString();
            if (val.Length < 5)
                return val;
            else
                return val.Substring(0, 5);
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string val = value.ToString();
            if (val.Length < 5)
                return val;
            else
                return val.Substring(0, 5);
        }
    }
</code>```

答:
This should work:

Xaml:

```<code><TextBox Text="{Binding TextToDisplay}" />
</code>```

Code:

```<code>    private const int maxLength = 5;
    private string _textToDisplay = "Hello SO";
    public string TextToDisplay
    {
        get
        {
            if(_textToDisplay.Length > maxLength)
            {
                return _textToDisplay.Substring(0, maxLength);
            }
            return _textToDisplay;
        }
        set
        {
            _textToDisplay = value;
            RaiseProperyChanged();
        }
    }
</code>```

Body:
I know that you can limit the input characters of TextBox from user by setting MaxLength property.

Is there a similar way to limit the number of characters shown in Text when the Text is updated with Binding? For example, when it is updated from Binding just show the first 5 characters and leave the rest?

Update:
Thanks for all the info, I got inspired by your recommendation and in the end did it with a converter. Here is how I did it, if someone wants to use it later.

    public class StringLimiter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string val = value.ToString();
            if (val.Length < 5)
                return val;
            else
                return val.Substring(0, 5);
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string val = value.ToString();
            if (val.Length < 5)
                return val;
            else
                return val.Substring(0, 5);
        }
    }

Body:
This should work:

Xaml:

<TextBox Text="{Binding TextToDisplay}" />

Code:

    private const int maxLength = 5;
    private string _textToDisplay = "Hello SO";
    public string TextToDisplay
    {
        get
        {
            if(_textToDisplay.Length > maxLength)
            {
                return _textToDisplay.Substring(0, maxLength);
            }
            return _textToDisplay;
        }
        set
        {
            _textToDisplay = value;
            RaiseProperyChanged();
        }
    }

ContentLicense: CC BY-SA 4.0


问:
Html.ActionLink not appending server url
I am working on MVC application where I need to show hyperlink. I am using

```<code>@Html.ActionLink
</code>```

problem is that , its rendering localhost url on server.

E.g. my code is as below

```<code><td>@Html.ActionLink(@Model.ID.ToString(), "Edit","AIQs", new { id = @Model.ID}, new { @class = "forgot-txt" })</td>
</code>```

but hyperlink URL , its generating is :

```<code>https://localhost/aim/AIQs/Edit?id=101
</code>```

It should be server url instead of localhost

答:
You can force your host name into actionlink according to your mind:

```<code>@Html.ActionLink("Go to contact page", "Edit", "AIQs", "yourprotocol", "yourhostname", "anchorname", routeValues, attributes)
</code>```

Also you can see this useful article:
https://msdn.microsoft.com/en-us/library/dd492938(v=vs.118).aspx

Body:
I am working on MVC application where I need to show hyperlink. I am using

@Html.ActionLink

problem is that , its rendering localhost url on server.

E.g. my code is as below

@Html.ActionLink(@Model.ID.ToString(), "Edit","AIQs", new { id = @Model.ID}, new { @class = "forgot-txt" })

but hyperlink URL , its generating is :

https://localhost/aim/AIQs/Edit?id=101

It should be server url instead of localhost

Body:
You can force your host name into actionlink according to your mind:

@Html.ActionLink("Go to contact page", "Edit", "AIQs", "yourprotocol", "yourhostname", "anchorname", routeValues, attributes)

Also you can see this useful article:
https://msdn.microsoft.com/en-us/library/dd492938(v=vs.118).aspx


问:
String size in Grails too big for database field
I have Message domain class that is used to send an email to site administrators

```<code>class Message {

  String name
  String subject
  String body

}
</code>```

I thought String would not have a maximum size but when people put in messages that are too big then I see exceptions in my log files.  For now I put a constraint in to limit the size of the message to 250 but cannot make it bigger or else the save fails.  I am using PostgreSQL 9.1.1 and Grails 1.3.7.  Does anyone know a way to fix this?

答:
The max size of a VARCHAR is set in the database, Grails doesn't have any say in the matter. What you can do is tell Grails what you need, and it will generate DDL that uses a clob instead of a string.

Change the mapping for the column to use type: "text", while adding the maxSize you want in your constraints. Grails will figure out from this that it should set the column data type to clob.

(Generally a clob field will hold up to 4GB, though some databases allow changing that.)

Body:
I have Message domain class that is used to send an email to site administrators

class Message {

  String name
  String subject
  String body

}

I thought String would not have a maximum size but when people put in messages that are too big then I see exceptions in my log files.  For now I put a constraint in to limit the size of the message to 250 but cannot make it bigger or else the save fails.  I am using PostgreSQL 9.1.1 and Grails 1.3.7.  Does anyone know a way to fix this?


问:
How do I add indeterminate state in my custom checkbox?
I want to add indeterminate state in my custom checkbox.

True

False

[-]          <-- I want to have [-] value for indeterminate state when user clicks it third time

Here code

/* The container */
.container {
    display: block;
    position: relative;
    padding-left: 35px;
    margin-bottom: 12px;
    cursor: pointer;
    font-size: 22px;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

/* Hide the browser's default checkbox */
.container input {
    position: absolute;
    opacity: 0;
}

/* Create a custom checkbox */
.checkmark {
    position: absolute;
    top: 0;
    left: 0;
    height: 25px;
    width: 25px;
    background-color: #eee;
}

/* On mouse-over, add a grey background color */
.container:hover input ~ .checkmark {
    background-color: #ccc;
}

/* When the checkbox is checked, add a blue background */
.container input:checked ~ .checkmark {
    background-color: #2196F3;
}

/* Create the checkmark/indicator (hidden when not checked) */
.checkmark:after {
    content: "";
    position: absolute;
    display: none;
}

/* Show the checkmark when checked */
.container input:checked ~ .checkmark:after {
    display: block;
}

/* Style the checkmark/indicator */
.container .checkmark:after {
    left: 9px;
    top: 5px;
    width: 5px;
    height: 10px;
    border: solid white;
    border-width: 0 3px 3px 0;
    -webkit-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    transform: rotate(45deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<body>

<h1>Custom Checkbox</h1>
<label class="container">
  <input type="checkbox" checked="checked">
  <span class="checkmark"></span>
</label>

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

答:
Regular checkbox is not capable of doing it. You need to use a flag for this. What I would do is to use a counter flag, that is tied to the element:

$(function () {
  $(".check").data("state", 0).addClass("unchecked");
  $(".multi-checkbox").click(function () {
    var states = ["unchecked", "partial", "checked"];
    var curState = $(this).find(".check").data("state");
    curState++;
    $(this).find(".check").removeClass("unchecked partial checked").addClass(states[curState % states.length]).data("state", curState % states.length);
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.multi-checkbox .check {display: inline-block; vertical-align: top; width: 15px; height: 15px; border: 1px solid #333; margin: 3px;}
.multi-checkbox .check.unchecked {background: #fff;}
.multi-checkbox .check.partial {background: #ccc;}
.multi-checkbox .check.checked {background: #000;}</code>```

  Check me

```

I just wrote this snippet for this answer. Let me know if you have any questions. With font awesome, we can do it in a better way.

Body:
I want to add indeterminate state in my custom checkbox.

True

False

[-]          <-- I want to have [-] value for indeterminate state when user clicks it third time

Here code

/* The container */
.container {
    display: block;
    position: relative;
    padding-left: 35px;
    margin-bottom: 12px;
    cursor: pointer;
    font-size: 22px;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

/* Hide the browser's default checkbox */
.container input {
    position: absolute;
    opacity: 0;
}

/* Create a custom checkbox */
.checkmark {
    position: absolute;
    top: 0;
    left: 0;
    height: 25px;
    width: 25px;
    background-color: #eee;
}

/* On mouse-over, add a grey background color */
.container:hover input ~ .checkmark {
    background-color: #ccc;
}

/* When the checkbox is checked, add a blue background */
.container input:checked ~ .checkmark {
    background-color: #2196F3;
}

/* Create the checkmark/indicator (hidden when not checked) */
.checkmark:after {
    content: "";
    position: absolute;
    display: none;
}

/* Show the checkmark when checked */
.container input:checked ~ .checkmark:after {
    display: block;
}

/* Style the checkmark/indicator */
.container .checkmark:after {
    left: 9px;
    top: 5px;
    width: 5px;
    height: 10px;
    border: solid white;
    border-width: 0 3px 3px 0;
    -webkit-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    transform: rotate(45deg);
}

Custom Checkbox

  <input type="checkbox" checked="checked">

Body:
Regular checkbox is not capable of doing it. You need to use a flag for this. What I would do is to use a counter flag, that is tied to the element:

$(function () {
  $(".check").data("state", 0).addClass("unchecked");
  $(".multi-checkbox").click(function () {
    var states = ["unchecked", "partial", "checked"];
    var curState = $(this).find(".check").data("state");
    curState++;
    $(this).find(".check").removeClass("unchecked partial checked").addClass(states[curState % states.length]).data("state", curState % states.length);
  });
});

.multi-checkbox .check {display: inline-block; vertical-align: top; width: 15px; height: 15px; border: 1px solid #333; margin: 3px;}
.multi-checkbox .check.unchecked {background: #fff;}
.multi-checkbox .check.partial {background: #ccc;}
.multi-checkbox .check.checked {background: #000;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="multi-checkbox">
  <span class="check"></span>
  Check me
</div>

I just wrote this snippet for this answer. Let me know if you have any questions. With font awesome, we can do it in a better way.


问:
Estimated covariance matrices of parameters in lfe
I am trying to back out the estimated covariances for a set of linear fixed effects models estimated using the felm function from the lfe package, but I am struggling.

A small example might explain my problem:

```<code>library(lfe)
data("Produc", package = "plm")
femodel <- felm(log(gsp) ~ log(pcap) + log(pc) + log(emp) + unemp |
state | 0 | state,
data=Produc)
</code>```

The femodel has an element called clustervcv, which is as follows:

```<code>femodel$clustervcv
           log(pcap)       log(pc)      log(emp)         unemp
log(pcap)  3.964787e-03 -7.604048e-04 -0.002501062 -7.940638e-05
log(pc)   -7.604048e-04  4.153134e-03 -0.003951458 -9.809748e-05
log(emp)  -2.501062e-03 -3.951458e-03  0.007265777  1.724270e-04
unemp     -7.940638e-05 -9.809748e-05  0.000172427  6.786427e-06
</code>```

At the same time the summary of femodel looks as follows:

```<code>             Estimate Cluster s.e.    t value     Pr(>|t|)
log(pcap) -0.026149654  0.062966551 -0.4152944 6.780430e-01
log(pc)    0.292006925  0.064444814  4.5311159 6.806845e-06
log(emp)   0.768159473  0.085239526  9.0117755 1.601430e-18
unemp     -0.005297741  0.002605077 -2.0336216 4.233485e-02
</code>```

I am pretty sure that Cluster s.e.'s in the summary are a function of the diagonal elements of the robustvcv and some degrees of freedom. I just cannot figure out where to dig out the relevant degrees of freedom, and what the function is.

答:
ok blush, thanks a lot lmo for pointing out my stupidity. Seems that I was confused by all the different vcv's that the model object contains.

Just in case someone else is as confused as I was, here's how summary.felm chooses which covariance matrix to use:

If the clustering variable (= the variable after the third pipe in
the formula experssion) != 0, clustervcv element is used,

if the clustering variable is 0, vcv is used,

and if the clustering variable is 0, and summary() function has the parameter 'robust=T', robustvcv is used to calculate the std errors.

Body:
I am trying to back out the estimated covariances for a set of linear fixed effects models estimated using the felm function from the lfe package, but I am struggling.

A small example might explain my problem:

library(lfe)
data("Produc", package = "plm")
femodel <- felm(log(gsp) ~ log(pcap) + log(pc) + log(emp) + unemp |
state | 0 | state,
data=Produc)

The femodel has an element called clustervcv, which is as follows:

femodel$clustervcv
           log(pcap)       log(pc)      log(emp)         unemp
log(pcap)  3.964787e-03 -7.604048e-04 -0.002501062 -7.940638e-05
log(pc)   -7.604048e-04  4.153134e-03 -0.003951458 -9.809748e-05
log(emp)  -2.501062e-03 -3.951458e-03  0.007265777  1.724270e-04
unemp     -7.940638e-05 -9.809748e-05  0.000172427  6.786427e-06

At the same time the summary of femodel looks as follows:

             Estimate Cluster s.e.    t value     Pr(>|t|)
log(pcap) -0.026149654  0.062966551 -0.4152944 6.780430e-01
log(pc)    0.292006925  0.064444814  4.5311159 6.806845e-06
log(emp)   0.768159473  0.085239526  9.0117755 1.601430e-18
unemp     -0.005297741  0.002605077 -2.0336216 4.233485e-02

I am pretty sure that Cluster s.e.'s in the summary are a function of the diagonal elements of the robustvcv and some degrees of freedom. I just cannot figure out where to dig out the relevant degrees of freedom, and what the function is.


问:
css problem with height
I've got a div that contains an unordered list that gets updated by an ajax query. It's used for a livesearch.

Now I have this problem that when I set the height of the div to a fixed height (let's say 200) that the results are shown as they should. But when I don't set the height, or set it to auto, the div has a height of 0 when the searchresults are added to the ul.

I think this has something to do with the ajaxquery and the browser not recognizing the new height, but I don't know how to set it the right way.

How can I fix this?

Thanks in advance,

答: Try adding some dummy content statically on the html page and see if the height is still 0. If it is then you have a CSS issue. Most probably the contents of the div (list) are absolute positioned so the parent div cannot know the list's height.</p>

ContentLicense: CC BY-SA 2.5

Title: css problem with height


问:
Connecting PHP with node.js/javascript
I have to implement knapsack problem algorithm on my site that's based on PHP. I Thought that I will make it in JavaScript and I have ran into a problem. I'm taking data that I need to take into this algorithm from MySQL, and JavaScript just can't do this. So I managed to do this by adding connector from Node.js. The algorithm works when user is giving some input. I made an form in HTML just to grab input and use it as parameter in my function. The problem is now that whole website is wrote in PHP and I can't connect it with JavaScript, because of node.js part where I'm connecting to database. I want to ask if there is any way to use this.

To sum it up and make it clear:
website is in PHP, I want to make a simple HTML form to grab input from user into parameter function from JavaScript file. Problem is that my JavaScript file needs MySQL data to run so it becomes node.js. And from what I know it's not that easy to run node.js on PHP based webserver. Is it possible to combine PHP with JavaScript so PHP will load data from MySQL into JavaScript? What you guys suggest?

答:
In your php file, inject your results, something like this.

```<code><?php
// function that handle form data and returns results from mysql
// let's call it my_data_function
$results = my_data_function();
?>

<script type="text/javascript">
  var mysql_data = <?php echo json_enode($results)?>
  my_js_function(mysql_data)
</script>
</code>```

This is the old school way, then there was ajax, now we are talking REST API.

Hope this helps.

Let me know if you need more help.

Title: Connecting PHP with node.js/javascript

Body:
In your php file, inject your results, something like this.

<?php
// function that handle form data and returns results from mysql
// let's call it my_data_function
$results = my_data_function();
?>

<script type="text/javascript">
  var mysql_data = <?php echo json_enode($results)?>
  my_js_function(mysql_data)
</script>

This is the old school way, then there was ajax, now we are talking REST API.

Hope this helps.

Let me know if you need more help.


问:
Semantic UI Card with image on the left
Is it possible using Semantic UI Card have the image on the left? The documentation shows example where the image is always on the top. What i want to obtain is something like the Semantic UI Item (but of course i want use cards), like this:

What i want to obtain is something like this:

As you can see the image is on the left and it is something similar to a Semantic UI card.

答:
The best you can do with semantic components would be this:

```<code><div class="ui card" style="max-width: 100%; min-width: 100%;">
    <div class="content" style="padding: 0;">
        <div class="ui items">
            <div class="item">
                <div class="ui medium image">
                    <img src="https://semantic-ui.com/images/wireframe/image.png">
                </div>
                <div class="content" style="padding: 1rem;">
                    <a class="header">12 Years a Slave</a>
                    <div class="meta">
                        <span class="cinema">Union Square 14</span>
                    </div>
                    <div class="description">
                        <p></p>
                    </div>
                    <div class="extra">
                        <div class="ui label">IMAX</div>
                        <div class="ui label"><i class="globe icon"></i> Additional Languages</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="extra content">
        <a>
            More Info
        </a>
    </div>
</div>
</code>```

I have changed the padding on the content but that's the only custom CSS used.

To get it to look exactly like your image you will need to make your own component/style it your self.

Title: Semantic UI Card with image on the left

Body:
The best you can do with semantic components would be this:

<div class="ui card" style="max-width: 100%; min-width: 100%;">
    <div class="content" style="padding: 0;">
        <div class="ui items">
            <div class="item">
                <div class="ui medium image">
                    <img src="https://semantic-ui.com/images/wireframe/image.png">
                </div>
                <div class="content" style="padding: 1rem;">
                    <a class="header">12 Years a Slave</a>
                    <div class="meta">
                        <span class="cinema">Union Square 14</span>
                    </div>
                    <div class="description">
                        <p></p>
                    </div>
                    <div class="extra">
                        <div class="ui label">IMAX</div>
                        <div class="ui label"><i class="globe icon"></i> Additional Languages</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="extra content">
        <a>
            More Info
        </a>
    </div>
</div>

I have changed the padding on the content but that's the only custom CSS used.

To get it to look exactly like your image you will need to make your own component/style it your self.


问:
Trying to implement a jacobian matrix in python 2.7
I am working on a project that does some simulation and analysis for some buses on a circuit and I am required to implement a jacobian matrix like the one in the picture below in python

Jacobian matrix

I am still a beginner and i am trying to get some ideas on whats the best way to implement the matrix,i have been reading other posts here and most of them suggest using numpy, which i haven't been able to install ( i have windows 10 64bit). I would appreciate any help !

答:
You have to find a way to install numpy on Windows if you want to use python it is full of useful methods and I should say essential
check here Installing Numpy on 64bit Windows 7 with Python 2.7.3 it may helps you (even if it's only Windows seven you can actually try).

But if you plan on working with python you should try one of the releases of Linux (ubuntu e.g.) which are easy to install and open source.

For the calculus of the Jacobian matrix you can still implement it "by-hand" which is getting the step of a function with respect to each variable.


问:
Is there any way to make R Shiny support multiple users? I'm talking about hundreds of concurrent users
Is there any way to make R Shiny support multiple users? I'm talking about hundreds of concurrent users.
To add some context: I'm not talking about Authentication (username / password). That will be taken care of by Auth0 (see auth0.com). So AFTER they are logged in, I see that Shiny Server does not pass the username to the Shiny session (maybe deliberately, so that you are forced to purchase the Commercial license to Shiny Server?).My question is more about : a) how do I make it recognize the username of the logged in user? b) will it scale to hundreds of concurrent (simultaneous) users?</p>

答:
https://www.shinyproxy.io/ attempts to solve problem b): it spawns a Docker container per application and per user. It should scale well if you give it enough resources (unfortunately it's difficult to estimate what "enough" is beforehand... You should run your own tests).

I'm not sure about problem a) but Shinyproxy deals well with authentication of users.


问:
Next and previous not working properly using jQuery
I am working on the next and previous section. When I clicked on next button then it's displaying the next div but it's not working properly because Next button is working infinit.

Same as the previous button. I need to hide the previous button on page load when the user clicked on next button or scroll the mouse wheel than I have to display the previous button.

I tried some code

new WOW().init();
 (function() {
    function scrollHorizontally(e) {
        e = window.event || e;
        var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
        document.getElementById('gentags').scrollLeft -= (delta*40); // Multiplied by 40
        e.preventDefault();
    }
    if (document.getElementById('gentags').addEventListener) {
        // IE9, Chrome, Safari, Opera
        document.getElementById('gentags').addEventListener("mousewheel", scrollHorizontally, false);
        // Firefox
        document.getElementById('gentags').addEventListener("DOMMouseScroll", scrollHorizontally, false);
    } else {
        // IE 6/7/8
        document.getElementById('gentags').attachEvent("onmousewheel", scrollHorizontally);
    }
})();

$('.navigation_right').click(function() {
    $('.current').removeClass('current').hide()
        .next().show().addClass('current');
    if ($('.current').hasClass('last')) {
        $('.navigation_right').attr('disabled', true);
    }
    $('.navigation_left').attr('disabled', null);
});

$('.navigation_left').click(function() {
    $('.current').removeClass('current').hide()
        .prev().show().addClass('current');
    if ($('.current').hasClass('first')) {
        $('.navigation_left').attr('disabled', true);
    }
    $('.navigation_right').attr('disabled', null);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>  #gentags {
position:fixed;
margin-top: -.25em;
display: inline-block;
width: 100%;
overflow: hidden;
}

#gentags > div{
    overflow: hidden;
    width:250%;
}

::-webkit-scrollbar {
    width: 0px;  /* remove scrollbar space */
    background: transparent;  /* optional: just make scrollbar invisible */
}
/* optional: show position indicator in red */
::-webkit-scrollbar-thumb {
    background: transparent;
}

.horizontal_scroll .full_screen_100 article{
    width: 11.58%;
    height: 100%;
    float:left;
    border-left: solid 1px #E2E2E2;

}
.active_div{

display: none;
}

  /*Navigation style*/
  .horizontal_scroll_icon_pre_next {
    bottom: 50px;
    left: 0;

    position: fixed;

    width: 100%;
    height: 0;
   /* padding: 0 20px;*/
}
  .horizontal_scroll_icon_pre_next button{
  background-color: transparent;
border: none;
font-size: 0;
color: #7b7b7b;
display: none;
outline: 0;
cursor: pointer;
}
.horizontal_scroll_icon_pre_next button.navigation_left
{
 float: left;
}
.horizontal_scroll_icon_pre_next button.navigation_right
{
 float:right;
}

.horizontal_scroll_icon_pre_next button.active {
    display: block;
}
.horizontal_scroll_icon_pre_next button span {

    font-size: 30px;
}</code>```

 <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/animatecss/3.5.2/animate.min.css">
     <link rel="stylesheet" href="https://cdn.linearicons.com/free/1.0.0/icon-font.min.css">

I want to display this div when articles 7 comes on screen

01
Hover me and scroll mouse wheel

02
Hover me and scroll mouse wheel

03
Hover me and scroll mouse wheel

04
Hover me and scroll mouse wheel

05
Hover me and scroll mouse wheel

06
Hover me and scroll mouse wheel

07
Hover me and scroll mouse wheel

08
Hover me and scroll mouse wheel

        <button class="navigation_left active">Previous</button>
        <button class="navigation_right active">Next</button>

 ```

答:
try with some changes in code

new WOW().init();
(function() {
  function scrollHorizontally(e) {
e = window.event || e;
var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
document.getElementById('gentags').scrollLeft -= (delta * 40); // Multiplied by 40
e.preventDefault();
  }
  if (document.getElementById('gentags').addEventListener) {
// IE9, Chrome, Safari, Opera
document.getElementById('gentags').addEventListener("mousewheel", scrollHorizontally, false);
// Firefox
document.getElementById('gentags').addEventListener("DOMMouseScroll", scrollHorizontally, false);
  } else {
// IE 6/7/8
document.getElementById('gentags').attachEvent("onmousewheel", scrollHorizontally);
  }
})();

$('.navigation_right').click(function() {
  var current = $('.current');
  var nextEl = current.next();

   if($('.current').hasClass('last'))
   {
 $('.navigation_right').removeClass('active');
 $('.navigation_left').addClass('active');
   }
  if(nextEl.length > 0) {
current.removeClass('current').hide();
nextEl.addClass('current').show();
  }
});

$('.navigation_left').click(function() {
  var current = $('.current');
  var prevEL = current.prev();
if($('.current').hasClass('first'))
{
 $('.navigation_left').removeClass('active');
$('.navigation_right').addClass('active');
}
  if(prevEL.length > 0) {
current.removeClass('current');
prevEL.addClass('current').show();
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#gentags {
  position: fixed;
  margin-top: -.25em;
  display: inline-block;
  width: 100%;
  overflow: hidden;
}

#gentags>div {
  overflow: hidden;
  width: 250%;
}

::-webkit-scrollbar {
  width: 0px;
  /* remove scrollbar space */
  background: transparent;
  /* optional: just make scrollbar invisible */
}

/* optional: show position indicator in red */

::-webkit-scrollbar-thumb {
  background: transparent;
}

.horizontal_scroll .full_screen_100 article {
  width: 11.58%;
  height: 100%;
  float: left;
  border-left: solid 1px #E2E2E2;
}

.active_div {
  display: none;
}

/*Navigation style*/

.horizontal_scroll_icon_pre_next {
  bottom: 50px;
  left: 0;
  position: fixed;
  width: 100%;
  height: 0;
  /* padding: 0 20px;*/
}

.horizontal_scroll_icon_pre_next button {
  background-color: transparent;
  border: none;
  font-size: 0;
  color: #7b7b7b;
  display: none;
  outline: 0;
  cursor: pointer;
}

.horizontal_scroll_icon_pre_next button.navigation_left {
  float: left;
}

.horizontal_scroll_icon_pre_next button.navigation_right {
  float: right;
}

.horizontal_scroll_icon_pre_next button.active {
  display: block;
}

.horizontal_scroll_icon_pre_next button span {
  font-size: 30px;
}</code>```

<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/animatecss/3.5.2/animate.min.css">
<link rel="stylesheet" href="https://cdn.linearicons.com/free/1.0.0/icon-font.min.css">

I want to display this div when articles 7 comes on screen

01
Hover me and scroll mouse wheel

02
Hover me and scroll mouse wheel

03
Hover me and scroll mouse wheel

04
Hover me and scroll mouse wheel

05
Hover me and scroll mouse wheel

06
Hover me and scroll mouse wheel

07
Hover me and scroll mouse wheel

08
Hover me and scroll mouse wheel

  <button class="navigation_left active">Previous</button>
  <button class="navigation_right active">Next</button>

```

Body:
I am working on the next and previous section. When I clicked on next button then it's displaying the next div but it's not working properly because Next button is working infinit.

Same as the previous button. I need to hide the previous button on page load when the user clicked on next button or scroll the mouse wheel than I have to display the previous button.

I tried some code

new WOW().init();
 (function() {
    function scrollHorizontally(e) {
        e = window.event || e;
        var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
        document.getElementById('gentags').scrollLeft -= (delta*40); // Multiplied by 40
        e.preventDefault();
    }
    if (document.getElementById('gentags').addEventListener) {
        // IE9, Chrome, Safari, Opera
        document.getElementById('gentags').addEventListener("mousewheel", scrollHorizontally, false);
        // Firefox
        document.getElementById('gentags').addEventListener("DOMMouseScroll", scrollHorizontally, false);
    } else {
        // IE 6/7/8
        document.getElementById('gentags').attachEvent("onmousewheel", scrollHorizontally);
    }
})();

$('.navigation_right').click(function() {
    $('.current').removeClass('current').hide()
        .next().show().addClass('current');
    if ($('.current').hasClass('last')) {
        $('.navigation_right').attr('disabled', true);
    }
    $('.navigation_left').attr('disabled', null);
});

$('.navigation_left').click(function() {
    $('.current').removeClass('current').hide()
        .prev().show().addClass('current');
    if ($('.current').hasClass('first')) {
        $('.navigation_left').attr('disabled', true);
    }
    $('.navigation_right').attr('disabled', null);
});

  #gentags {
position:fixed;
margin-top: -.25em;
display: inline-block;
width: 100%;
overflow: hidden;
}

#gentags > div{
    overflow: hidden;
    width:250%;
}

::-webkit-scrollbar {
    width: 0px;  /* remove scrollbar space */
    background: transparent;  /* optional: just make scrollbar invisible */
}
/* optional: show position indicator in red */
::-webkit-scrollbar-thumb {
    background: transparent;
}

.horizontal_scroll .full_screen_100 article{
    width: 11.58%;
    height: 100%;
    float:left;
    border-left: solid 1px #E2E2E2;

}
.active_div{

display: none;
}

  /*Navigation style*/
  .horizontal_scroll_icon_pre_next {
    bottom: 50px;
    left: 0;

    position: fixed;

    width: 100%;
    height: 0;
   /* padding: 0 20px;*/
}
  .horizontal_scroll_icon_pre_next button{
  background-color: transparent;
border: none;
font-size: 0;
color: #7b7b7b;
display: none;
outline: 0;
cursor: pointer;
}
.horizontal_scroll_icon_pre_next button.navigation_left
{
 float: left;
}
.horizontal_scroll_icon_pre_next button.navigation_right
{
 float:right;
}

.horizontal_scroll_icon_pre_next button.active {
    display: block;
}
.horizontal_scroll_icon_pre_next button span {

    font-size: 30px;
}

 <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/animatecss/3.5.2/animate.min.css">
     <link rel="stylesheet" href="https://cdn.linearicons.com/free/1.0.0/icon-font.min.css">

I want to display this div when articles 7 comes on screen

01
Hover me and scroll mouse wheel

02
Hover me and scroll mouse wheel

03
Hover me and scroll mouse wheel

04
Hover me and scroll mouse wheel

05
Hover me and scroll mouse wheel

06
Hover me and scroll mouse wheel

07
Hover me and scroll mouse wheel

08
Hover me and scroll mouse wheel

        <button class="navigation_left active">Previous</button>
        <button class="navigation_right active">Next</button>

Body:
try with some changes in code

new WOW().init();
(function() {
  function scrollHorizontally(e) {
e = window.event || e;
var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
document.getElementById('gentags').scrollLeft -= (delta * 40); // Multiplied by 40
e.preventDefault();
  }
  if (document.getElementById('gentags').addEventListener) {
// IE9, Chrome, Safari, Opera
document.getElementById('gentags').addEventListener("mousewheel", scrollHorizontally, false);
// Firefox
document.getElementById('gentags').addEventListener("DOMMouseScroll", scrollHorizontally, false);
  } else {
// IE 6/7/8
document.getElementById('gentags').attachEvent("onmousewheel", scrollHorizontally);
  }
})();

$('.navigation_right').click(function() {
  var current = $('.current');
  var nextEl = current.next();

   if($('.current').hasClass('last'))
   {
 $('.navigation_right').removeClass('active');
 $('.navigation_left').addClass('active');
   }
  if(nextEl.length > 0) {
current.removeClass('current').hide();
nextEl.addClass('current').show();
  }
});

$('.navigation_left').click(function() {
  var current = $('.current');
  var prevEL = current.prev();
if($('.current').hasClass('first'))
{
 $('.navigation_left').removeClass('active');
$('.navigation_right').addClass('active');
}
  if(prevEL.length > 0) {
current.removeClass('current');
prevEL.addClass('current').show();
  }
});

#gentags {
  position: fixed;
  margin-top: -.25em;
  display: inline-block;
  width: 100%;
  overflow: hidden;
}

#gentags>div {
  overflow: hidden;
  width: 250%;
}

::-webkit-scrollbar {
  width: 0px;
  /* remove scrollbar space */
  background: transparent;
  /* optional: just make scrollbar invisible */
}

/* optional: show position indicator in red */

::-webkit-scrollbar-thumb {
  background: transparent;
}

.horizontal_scroll .full_screen_100 article {
  width: 11.58%;
  height: 100%;
  float: left;
  border-left: solid 1px #E2E2E2;
}

.active_div {
  display: none;
}

/*Navigation style*/

.horizontal_scroll_icon_pre_next {
  bottom: 50px;
  left: 0;
  position: fixed;
  width: 100%;
  height: 0;
  /* padding: 0 20px;*/
}

.horizontal_scroll_icon_pre_next button {
  background-color: transparent;
  border: none;
  font-size: 0;
  color: #7b7b7b;
  display: none;
  outline: 0;
  cursor: pointer;
}

.horizontal_scroll_icon_pre_next button.navigation_left {
  float: left;
}

.horizontal_scroll_icon_pre_next button.navigation_right {
  float: right;
}

.horizontal_scroll_icon_pre_next button.active {
  display: block;
}

.horizontal_scroll_icon_pre_next button span {
  font-size: 30px;
}

<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/animatecss/3.5.2/animate.min.css">
<link rel="stylesheet" href="https://cdn.linearicons.com/free/1.0.0/icon-font.min.css">
<!--icon-->
<div class="active_div">
  <h2>I want to display this div when articles 7 comes on screen</h2>
</div>

<div id="gentags">
  <div class="horizontal_scroll">
    <div class="full_screen_100" id="left_scroll">
      <article class="wow fadeInUp first current">
        <div>
          <p class="scroll_number">01</p><span class="page_slogan">Hover me and scroll mouse wheel</span></div>
      </article>
      <article class="wow fadeInUp">
        <div>
          <p class="scroll_number">02</p><span class="page_slogan">Hover me and scroll mouse wheel </span></div>
      </article>
      <article class="wow fadeInUp">
        <div>
          <p class="scroll_number">03</p><span class="page_slogan">Hover me and scroll mouse wheel</span></div>
      </article>
      <article class="wow fadeInUp">
        <div>
          <p class="scroll_number">04</p><span class="page_slogan">Hover me and scroll mouse wheel</span></div>
      </article>
      <article class="wow fadeInUp">
        <div>
          <p class="scroll_number">05</p><span class="page_slogan">Hover me and scroll mouse wheel</span></div>
      </article>
      <article class="wow fadeInUp">
        <div>
          <p class="scroll_number">06</p><span class="page_slogan">Hover me and scroll mouse wheel</span></div>
      </article>
      <article class="wow fadeInUp">
        <div>
          <p class="scroll_number">07</p><span class="page_slogan">Hover me and scroll mouse wheel</span></div>
      </article>
      <article class="wow fadeInUp last">
        <div>
          <p class="scroll_number">08</p><span class="page_slogan">Hover me and scroll mouse wheel</span></div>
      </article>
    </div>
  </div>
</div>

<div class="horizontal_scroll_icon_pre_next">
  <button class="navigation_left active"><span class="lnr lnr-arrow-left"></span>Previous</button>
  <button class="navigation_right active"><span class="lnr lnr-arrow-right"></span>Next</button>
</div>
<!--horizontal_scroll_navigation-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/wow/1.1.2/wow.min.js"></script>


问:
Does Distinct() method keep original ordering of sequence intact?
I want to remove duplicates from list, without changing order of unique elements in the list.

Jon Skeet & others have suggested to use the following:

```<code>list = list.Distinct().ToList();
</code>```

Reference:

How to remove duplicates from a List<T>?

Remove duplicates from a List<T> in C#

Is it guaranteed that the order of unique elements would be same as before? If yes, please give a reference that confirms this as I couldn't find anything on it in documentation.

答:
In the .NET Framework 3.5, disassembling the CIL of the Linq-to-Objects implementation of Distinct() shows that the order of elements is preserved - however this is not documented behavior.

I did a little investigation with Reflector. After disassembling System.Core.dll, Version=3.5.0.0 you can see that Distinct() is an extension method, which looks like this:

```<code>public static class Emunmerable
{
    public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source)
    {
        if (source == null)
            throw new ArgumentNullException("source");

        return DistinctIterator<TSource>(source, null);
    }
}
</code>```

So, interesting here is DistinctIterator, which implements IEnumerable and IEnumerator. Here is simplified (goto and lables removed) implementation of this IEnumerator:

```<code>private sealed class DistinctIterator<TSource> : IEnumerable<TSource>, IEnumerable, IEnumerator<TSource>, IEnumerator, IDisposable
{
    private bool _enumeratingStarted;
    private IEnumerator<TSource> _sourceListEnumerator;
    public IEnumerable<TSource> _source;
    private HashSet<TSource> _hashSet;
    private TSource _current;

    private bool MoveNext()
    {
        if (!_enumeratingStarted)
        {
            _sourceListEnumerator = _source.GetEnumerator();
            _hashSet = new HashSet<TSource>();
            _enumeratingStarted = true;
        }

        while(_sourceListEnumerator.MoveNext())
        {
            TSource element = _sourceListEnumerator.Current;

             if (!_hashSet.Add(element))
                 continue;

             _current = element;
             return true;
        }

        return false;
    }

    void IEnumerator.Reset()
    {
        throw new NotSupportedException();
    }

    TSource IEnumerator<TSource>.Current
    {
        get { return _current; }
    }

    object IEnumerator.Current
    {
        get { return _current; }
    }
}
</code>```

As you can see - enumerating goes in order provided by source enumerable (list, on which we are calling Distinct). Hashset is used only for determining whether we already returned such element or not. If not, we are returning it, else - continue enumerating on source.

So, it is guaranteed, that Distinct() will return elements exactly in same order, which are provided by collection to which Distinct was applied.

Body:
I want to remove duplicates from list, without changing order of unique elements in the list.

Jon Skeet & others have suggested to use the following:

list = list.Distinct().ToList();

Reference:

How to remove duplicates from a List<T>?

Remove duplicates from a List<T> in C#

Is it guaranteed that the order of unique elements would be same as before? If yes, please give a reference that confirms this as I couldn't find anything on it in documentation.

Body:
In the .NET Framework 3.5, disassembling the CIL of the Linq-to-Objects implementation of Distinct() shows that the order of elements is preserved - however this is not documented behavior.

I did a little investigation with Reflector. After disassembling System.Core.dll, Version=3.5.0.0 you can see that Distinct() is an extension method, which looks like this:

public static class Emunmerable
{
    public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source)
    {
        if (source == null)
            throw new ArgumentNullException("source");

        return DistinctIterator<TSource>(source, null);
    }
}

So, interesting here is DistinctIterator, which implements IEnumerable and IEnumerator. Here is simplified (goto and lables removed) implementation of this IEnumerator:

private sealed class DistinctIterator<TSource> : IEnumerable<TSource>, IEnumerable, IEnumerator<TSource>, IEnumerator, IDisposable
{
    private bool _enumeratingStarted;
    private IEnumerator<TSource> _sourceListEnumerator;
    public IEnumerable<TSource> _source;
    private HashSet<TSource> _hashSet;
    private TSource _current;

    private bool MoveNext()
    {
        if (!_enumeratingStarted)
        {
            _sourceListEnumerator = _source.GetEnumerator();
            _hashSet = new HashSet<TSource>();
            _enumeratingStarted = true;
        }

        while(_sourceListEnumerator.MoveNext())
        {
            TSource element = _sourceListEnumerator.Current;

             if (!_hashSet.Add(element))
                 continue;

             _current = element;
             return true;
        }

        return false;
    }

    void IEnumerator.Reset()
    {
        throw new NotSupportedException();
    }

    TSource IEnumerator<TSource>.Current
    {
        get { return _current; }
    }

    object IEnumerator.Current
    {
        get { return _current; }
    }
}

As you can see - enumerating goes in order provided by source enumerable (list, on which we are calling Distinct). Hashset is used only for determining whether we already returned such element or not. If not, we are returning it, else - continue enumerating on source.

So, it is guaranteed, that Distinct() will return elements exactly in same order, which are provided by collection to which Distinct was applied.


问:
Tranposing a table google sheet
In Google Sheet / google script / javascript, .
how can I convert my table

from

```<code>05/05/2017  Peter   Apple
05/05/2017  John    Banana
05/05/2017  Jake    Apple
05/06/2017  John    Apple
05/06/2017  Jake    Banana
05/06/2017  Peter   Banana
</code>```

to

```<code>      05/05/2017    05/06/2017
Peter   Apple        Banana
John    Banana       Apple
Jake    Apple        Banana
</code>```

TIA.

答:
```<code>1: Paste the table in B1 across D6.

2: In A1 enter this formula -> =ArrayFormula(C1:C&B1:B)

3. In F1, enter this -> =TRANSPOSE(unique({B:B}))

4. IN E2, enter this -> =UNIQUE(C:C)

5. In F2, enter this -> =ArrayFormula(iferror(VLOOKUP($E2:$E&F1,$A1:$D,4,0),""))
</code>```

<p>You can grad the formula in F2 across next columns to get the data. </p>

Title: Tranposing a table google sheet

Body:
In Google Sheet / google script / javascript, .
how can I convert my table

from

05/05/2017  Peter   Apple
05/05/2017  John    Banana
05/05/2017  Jake    Apple
05/06/2017  John    Apple
05/06/2017  Jake    Banana
05/06/2017  Peter   Banana

to

      05/05/2017    05/06/2017
Peter   Apple        Banana
John    Banana       Apple
Jake    Apple        Banana

TIA.

Body:
1: Paste the table in B1 across D6.

2: In A1 enter this formula -> =ArrayFormula(C1:C&B1:B)

3. In F1, enter this -> =TRANSPOSE(unique({B:B}))

4. IN E2, enter this -> =UNIQUE(C:C)

5. In F2, enter this -> =ArrayFormula(iferror(VLOOKUP($E2:$E&F1,$A1:$D,4,0),""))

You can grad the formula in F2 across next columns to get the data.


问:
Can't get div to stick to bottom of another div with position: absolute
I'm trying to get a div to stick to the bottom of another div using position: absolute and bottom:0; right:0, but it isn't working because there's still a small space left between the div and the bottom.

#weekly-product-container {
  margin-top: 91px;
  background: black;
  padding-top: 20px !important;
  width: 100vw;
  min-height: 500px;
  text-align: center;
  border-left: 1px solid #eee;
  display: flex;
  flex-direction: row;
  background-color: black;
  color: white;
  margin-top: 100px;
}
#triangle5 {
  width: 0px;
  height: 0px;
  border-left:  300px solid transparent;
  border-bottom:  200px solid red;
  border-bottom-right-radius: none;
  bottom: 0;
  position: absolute;
  right: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="weekly-product-container">
  <div id="triangle5"></div>
</div></code>```

答:
Set position: relative; on container:

#weekly-product-container {
  margin-top: 91px;
  background: black;
  padding-top: 20px !important;
  width: 100vw;
  min-height: 500px;
  text-align: center;
  border-left: 1px solid #eee;
  display: flex;
  flex-direction: row;
  background-color: black;
  color: white;
  margin-top: 100px;
  position: relative;
}
#triangle5 {
  width: 0px;
  height: 0px;
  border-left:  300px solid transparent;
  border-bottom:  200px solid red;
  border-bottom-right-radius: none;
  bottom: 0;
  position: absolute;
  right: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="weekly-product-container">
  <div id="triangle5"></div>
</div></code>```

Body:
Set position: relative; on container:

#weekly-product-container {
  margin-top: 91px;
  background: black;
  padding-top: 20px !important;
  width: 100vw;
  min-height: 500px;
  text-align: center;
  border-left: 1px solid #eee;
  display: flex;
  flex-direction: row;
  background-color: black;
  color: white;
  margin-top: 100px;
  position: relative;
}
#triangle5 {
  width: 0px;
  height: 0px;
  border-left:  300px solid transparent;
  border-bottom:  200px solid red;
  border-bottom-right-radius: none;
  bottom: 0;
  position: absolute;
  right: 0;
}

<div id="weekly-product-container">
  <div id="triangle5"></div>
</div>


答:
All you have to do, is add position: relative; to weekly-product-container and change bottom: 0; for triangle5:

```<code>#weekly-product-container {
    position: relative;
}

#triangle5 {
    position: absolute;
    bottom: 0;
}
</code>```

Here is an example: https://jsfiddle.net/cr29y1tc/30/

Title: Can't get div to stick to bottom of another div with position: absolute

Body:
I'm trying to get a div to stick to the bottom of another div using position: absolute and bottom:0; right:0, but it isn't working because there's still a small space left between the div and the bottom.

#weekly-product-container {
  margin-top: 91px;
  background: black;
  padding-top: 20px !important;
  width: 100vw;
  min-height: 500px;
  text-align: center;
  border-left: 1px solid #eee;
  display: flex;
  flex-direction: row;
  background-color: black;
  color: white;
  margin-top: 100px;
}
#triangle5 {
  width: 0px;
  height: 0px;
  border-left:  300px solid transparent;
  border-bottom:  200px solid red;
  border-bottom-right-radius: none;
  bottom: 0;
  position: absolute;
  right: 0;
}

Body:
All you have to do, is add position: relative; to weekly-product-container and change bottom: 0; for triangle5:

#weekly-product-container {
    position: relative;
}

#triangle5 {
    position: absolute;
    bottom: 0;
}

Here is an example: https://jsfiddle.net/cr29y1tc/30/


问:
Submenu in a navigation bar: li's width doesn't fit the text length
I have a navigation-bar with a submenu. The problem: the li's width in the submenu doesn't fit the text length. Why?

ul {
        margin: 0;
        padding: 0;
        list-style: none;
      }

      #nav-bar > li {
        float: left;
        position
      }

      .has-submenu {
        position: relative;
      }
      .submenu {
        position: absolute;

      }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="nav-bar">
      <li>Item 1</li>
      <li class="has-submenu">Item 2
        <ul class="submenu">
          <li>Subitem 1</li>
          <li>Subitem 2</li>
        </ul>
      </li>
      <li>Item 3</li>
    </ul></code>```

答:
Give white-space: nowrap; to .submenu li class.

ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

#nav-bar > li {
  float: left;
}

.has-submenu {
  position: relative;
}
.submenu {
  position: absolute;
}
.submenu li{
  white-space: nowrap;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="nav-bar">
  <li>Item 1</li>
  <li class="has-submenu">Item 2
    <ul class="submenu">
      <li>Subitem 1</li>
      <li>Subitem 2</li>
    </ul>
  </li>
  <li>Item 3</li>
</ul></code>```

Body:
I have a navigation-bar with a submenu. The problem: the li's width in the submenu doesn't fit the text length. Why?

ul {
        margin: 0;
        padding: 0;
        list-style: none;
      }

      #nav-bar > li {
        float: left;
        position
      }

      .has-submenu {
        position: relative;
      }
      .submenu {
        position: absolute;

      }

Item 1

Item 2

Subitem 1

Subitem 2

Item 3

Body:
Give white-space: nowrap; to .submenu li class.

ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

#nav-bar > li {
  float: left;
}

.has-submenu {
  position: relative;
}
.submenu {
  position: absolute;
}
.submenu li{
  white-space: nowrap;
}

<ul id="nav-bar">
  <li>Item 1</li>
  <li class="has-submenu">Item 2
    <ul class="submenu">
      <li>Subitem 1</li>
      <li>Subitem 2</li>
    </ul>
  </li>
  <li>Item 3</li>
</ul>


问:
ASP.NET Conditional Markup Rendering According to Web.config Key
I have a key in web.config as -

```<code><add key="IsDemo" value ="true"/>
</code>```

I want to show/hide markup based on above web.config entry for a non-server html tag without using code behind file (as there is no .cs file and there are no runat=server controls).
Something similar to following pseudo code:

```<code>IF ( IsDemo == "true" )
THEN
<tr>
    <td id="tdDemoSection" colspan="2" align="left" valign="top">
        <.....>
    </td>
</tr>
ENDIF
</code>```

Does anyone know that we can write such conditional logic in .aspx markup?
Please help!!!

EDIT:

Section I'm hiding or showing have some data like username and password. So, I do not want user to use Firebug or Web Developer Tools to see hidden markup. markup should not go to client side.

答:
If I understand it right, you don't want to use server-side (aspx components, with runat="server" attribute) and just want to control display of html on aspx page then try this solution.

Create a property in codebehind file (or better still in some other config helper class):

```<code>//IN C# (OR VB) file
protected string Demo{
    get{
            return ConfigurationManager.AppSettings["IsDemo"]=="true"?
                   "none":"block";
      }
}
</code>```

In aspx page:

```<code><tr style="display:<%= Demo%>;">
    <td>blah blah</td>
</tr>
</code>```

Body:
I have a key in web.config as -

<add key="IsDemo" value ="true"/>

I want to show/hide markup based on above web.config entry for a non-server html tag without using code behind file (as there is no .cs file and there are no runat=server controls).
Something similar to following pseudo code:

IF ( IsDemo == "true" )
THEN

        <.....>

ENDIF

Does anyone know that we can write such conditional logic in .aspx markup?
Please help!!!

EDIT:

Section I'm hiding or showing have some data like username and password. So, I do not want user to use Firebug or Web Developer Tools to see hidden markup. markup should not go to client side.

Body:
If I understand it right, you don't want to use server-side (aspx components, with runat="server" attribute) and just want to control display of html on aspx page then try this solution.

Create a property in codebehind file (or better still in some other config helper class):

//IN C# (OR VB) file
protected string Demo{
    get{
            return ConfigurationManager.AppSettings["IsDemo"]=="true"?
                   "none":"block";
      }
}

In aspx page:

<tr style="display:<%= Demo%>;">
    <td>blah blah</td>
</tr>


问:
Can't get pprint to work in clojure
Noob question, using Win7 64-bit, Clojure 1.2.0, Java 1.6.0_22

When I start clojure from command line, pprint function is easily available.

```<code>user=> pprint
#<pprint$pprint clojure.pprint$pprint@16dfa45>
user=> (pprint "hi")
"hi"
nil
user=>
</code>```

But when I try to use pprint from a file, I get an error.  This happens with and without namespace  (ns... :require...) as shown in pprint documentation

clj file as follows:

```<code>(ns whatevah
(:require clojure.pprint))

(pprint "hi")
</code>```

Error as follows:

```<code>C:\Users\mischw\code\Clojure>java -cp ";c:\users\mischw\code\clojure\classes\*;c:\Program Files (x86)\Java\SWT;c:\users\mischw\code\clojure\classes\bookcode\*" clojure.main swinglearn.clj
Exception in thread "main" java.lang.Exception: Unable to resolve symbol: pprint in this context (swinglearn.clj:14)
... 21 more

Output completed (0 sec consumed) - Normal Termination
</code>```

I don't understand the general idea of what's going on here.  Why does one work but not the other?  Does that have to do with namespaces?  Classpaths?  Some other simple fix?  Clearly noob questions, but I find this happens with a bunch of examples... I'm unable to run them even though it seems straightforward to import/use/require/include them.

答:
Here are a couple of examples:

;;how to use it with :require and :use

```<code>;; :require
(ns example.pprinter
    (:require [clojure.pprint :as pp]))

(def myname "John Smith")
(pp/pprint myname)
</code>```

```<code>;; :use
(ns example.pprinter
    (:use clojure.pprint))

(def myname "John Smith")
(pprint myname)
</code>```

Title: Can't get pprint to work in clojure

Body:
Noob question, using Win7 64-bit, Clojure 1.2.0, Java 1.6.0_22

When I start clojure from command line, pprint function is easily available.

user=> pprint
#<pprint$pprint clojure.pprint$pprint@16dfa45>
user=> (pprint "hi")
"hi"
nil
user=>

But when I try to use pprint from a file, I get an error.  This happens with and without namespace  (ns... :require...) as shown in pprint documentation

clj file as follows:

(ns whatevah
(:require clojure.pprint))

(pprint "hi")

Error as follows:

C:\Users\mischw\code\Clojure>java -cp ";c:\users\mischw\code\clojure\classes\*;c:\Program Files (x86)\Java\SWT;c:\users\mischw\code\clojure\classes\bookcode\*" clojure.main swinglearn.clj
Exception in thread "main" java.lang.Exception: Unable to resolve symbol: pprint in this context (swinglearn.clj:14)
... 21 more

Output completed (0 sec consumed) - Normal Termination

I don't understand the general idea of what's going on here.  Why does one work but not the other?  Does that have to do with namespaces?  Classpaths?  Some other simple fix?  Clearly noob questions, but I find this happens with a bunch of examples... I'm unable to run them even though it seems straightforward to import/use/require/include them.

Body:
Here are a couple of examples:

;;how to use it with :require and :use

;; :require
(ns example.pprinter
    (:require [clojure.pprint :as pp]))

(def myname "John Smith")
(pp/pprint myname)

;; :use
(ns example.pprinter
    (:use clojure.pprint))

(def myname "John Smith")
(pprint myname)


问:
Ionic Background Geolocation plugin causes error when building
I have an Ionic 2 app that worked fine. Now I made an update and when I try to build the APK I get an error.

```<code>* What went wrong:
        Execution failed for task ':transformClassesWithJarMergingForRelease'.
        > com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry:
        com/google/android/gms/iid/zzc.class
</code>```

The error tells me the problem but I don't know how to solve it. Where do I have to remove the duplicate?

This is related to the Ionic Background Geolocation plugin because if I remove that plugin the issue disappears.

答:
The background geolocation plugin depends on the Play Services library and the error message you posted above is indicative of a mismatch in versions of the Play Services library specified in the Gradle configuration (see here for a similar error). The likely cause is that you have another plugin in your project specifying a different Play Services version. The background geolocation plugin is specifying +, i.e. the most recent version (v11.6.0).

A possible solution is to install the cordova-android-play-services-gradle-release plugin into your project, which attempts to override the versions specified by plugins to resolve version collisions.

The background geolocation plugin also depends on the Android Support library, so after fixing the Play Services issue, you may encounter a similar problem with this. If so, you can try to use cordova-android-support-gradle-release to perform a similar override in the Gradle config.

Body:
I have an Ionic 2 app that worked fine. Now I made an update and when I try to build the APK I get an error.

* What went wrong:
        Execution failed for task ':transformClassesWithJarMergingForRelease'.
        > com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry:
        com/google/android/gms/iid/zzc.class

The error tells me the problem but I don't know how to solve it. Where do I have to remove the duplicate?

This is related to the Ionic Background Geolocation plugin because if I remove that plugin the issue disappears.


问:
What is Closure in Laravel?
I saw one Laravel function in middlewere:

```<code>public function handle($request, Closure $next, $guard = null)
{
    if (Auth::guard($guard)->check())
    {
       return redirect('/home');
    }

    return $next($request);
}
</code>```

What is Closure and what does it do?

答:
A Closure is an anonymous function. Closures are often used as callback methods and can be used as a parameter in a function.

If you take the following example:

```<code>function handle(Closure $closure) {
    $closure();
}

handle(function(){
    echo 'Hello!';
});
</code>```

We start by adding a Closure parameter the handle function. This will type hint us that the handle function takes a Closure.

We then call the handle function and pass a function as the first parameter.

By using $closure(); in the handle function we tell PHP to execute the given Closure which will then echo 'Hello!'

It is also possible to pass parameters into a Closure. We can do so by changing the Closure call in the handle function to pass on a parameter. In this example i'll just pass a string but this can be any variable.

The handle function now looks like

```<code>function handle(Closure $closure) {
    $closure('Hello World!');
}
</code>```

We now also need to modify the Closure itself to take the parameter. We do so by simply adding a parameter to the function. And then we pass that variable to the echo.

The function now looks like

```<code>handle(function($value){
    echo $value;
});
</code>```

Which will echo Hello World!

For more information you can check out these links:

http://php.net/manual/en/functions.anonymous.php

http://php.net/manual/en/class.closure.php

Title: What is Closure in Laravel?

Body:
I saw one Laravel function in middlewere:

public function handle($request, Closure $next, $guard = null)
{
    if (Auth::guard($guard)->check())
    {
       return redirect('/home');
    }

    return $next($request);
}

What is Closure and what does it do?

Body:
A Closure is an anonymous function. Closures are often used as callback methods and can be used as a parameter in a function.

If you take the following example:

function handle(Closure $closure) {
    $closure();
}

handle(function(){
    echo 'Hello!';
});

We start by adding a Closure parameter the handle function. This will type hint us that the handle function takes a Closure.

We then call the handle function and pass a function as the first parameter.

By using $closure(); in the handle function we tell PHP to execute the given Closure which will then echo 'Hello!'

It is also possible to pass parameters into a Closure. We can do so by changing the Closure call in the handle function to pass on a parameter. In this example i'll just pass a string but this can be any variable.

The handle function now looks like

function handle(Closure $closure) {
    $closure('Hello World!');
}

We now also need to modify the Closure itself to take the parameter. We do so by simply adding a parameter to the function. And then we pass that variable to the echo.

The function now looks like

handle(function($value){
    echo $value;
});

Which will echo Hello World!

For more information you can check out these links:

http://php.net/manual/en/functions.anonymous.php

http://php.net/manual/en/class.closure.php


问:
TypeError: unsupported operand type(s) for /: 'NoneType' and 'float'
I am new to Python. I am trying to recognize text from images from TensorFlow. When I try to run python gen.py in the terminal, I am getting a TypeError.

```
Traceback (most recent call last):
  File "gen.py", line 287, in
   for img_idx, (im, c, p) in enumerate(im_gen):
  File "gen.py", line 277, in generate_ims
   yield generate_im(random.choice(char_ims), num_bg_images)
  File "gen.py", line 239, in generate_im
   bg = generate_bg(num_bg_images)
  File "gen.py", line 226, in generate_bg
   bg = cv2.imread(fname, cv2.IMREAD_GRAYSCALE) / 255.
TypeError: unsupported operand type(s) for /: 'NoneType' and 'float'
```

答:
It looks like your code can't open image on that path

```<code>bg = cv2.imread(fname, cv2.IMREAD_GRAYSCALE) / 255
</code>```

The cv2.imread method returned None.

It's better to get the image first

```<code>image = cv2.imread(fname, cv2.IMREAD_GRAYSCALE)
if image is not None:
    bg = image / 255
</code>```

Also you can import the os module at the beginning to check that file exists

```<code>import os
# <your code...>
if !os.path.isfile(fname):
    raise Exception("File doesn't exist")

image = cv2.imread(fname, cv2.IMREAD_GRAYSCALE)
if image is not None:
    bg = image / 255
</code>```

Body:
I am new to Python. I am trying to recognize text from images from TensorFlow. When I try to run python gen.py in the terminal, I am getting a TypeError.

Traceback (most recent call last):
  File "gen.py", line 287, in
   for img_idx, (im, c, p) in enumerate(im_gen):
  File "gen.py", line 277, in generate_ims
   yield generate_im(random.choice(char_ims), num_bg_images)
  File "gen.py", line 239, in generate_im
   bg = generate_bg(num_bg_images)
  File "gen.py", line 226, in generate_bg
   bg = cv2.imread(fname, cv2.IMREAD_GRAYSCALE) / 255.
TypeError: unsupported operand type(s) for /: 'NoneType' and 'float'

Body:
It looks like your code can't open image on that path

bg = cv2.imread(fname, cv2.IMREAD_GRAYSCALE) / 255

The cv2.imread method returned None.

It's better to get the image first

image = cv2.imread(fname, cv2.IMREAD_GRAYSCALE)
if image is not None:
    bg = image / 255

Also you can import the os module at the beginning to check that file exists

import os
# <your code...>
if !os.path.isfile(fname):
    raise Exception("File doesn't exist")

image = cv2.imread(fname, cv2.IMREAD_GRAYSCALE)
if image is not None:
    bg = image / 255


问:
Aggregate yearly sum of selected months of a time series in R
I have a time series of monthly data over multiple years. Now I'd like to calculated different indices for each year like e.g. (i) the annual sum and (ii) the sum of specific months (July and August). I want to use the aggregate function in R and the zoo-package.

Calculating the yearly sum was not the problem...

```<code># Test dataset
z_test <-  as.zoo(ts(rnorm(200), start=c(1922,1), frequency=12))

# Yearly sum
as.year <- function(x) as.numeric(floor(as.yearmon(x)))
yearsum <- as.ts(aggregate(z_test, as.year, sum))
</code>```

..however, what is the best way to return the sum of specific months using aggregate? For example I would like to have the sum of July and August for each year (similar shape as yearsum)

```<code>JulAug_sum <-?
</code>```

答:
Hope this helps</p>

```<code>library(zoo)

# Test dataset
ts_test <-  as.zoo(ts(rnorm(200), start=c(1922,1), frequency=12))

# Yearly sum
as.year <- function(x) as.numeric(floor(as.yearmon(x)))
yearsum <- as.ts(aggregate(as.zoo(ts_test), as.year, sum))

df <- subset(ts_test, (cycle(ts_test) == 7 | cycle(ts_test) == 8))
JulAugsum <- as.ts(aggregate(as.zoo(df), as.year, sum))
</code>```

Body:
I have a time series of monthly data over multiple years. Now I'd like to calculated different indices for each year like e.g. (i) the annual sum and (ii) the sum of specific months (July and August). I want to use the aggregate function in R and the zoo-package.

Calculating the yearly sum was not the problem...

# Test dataset
z_test <-  as.zoo(ts(rnorm(200), start=c(1922,1), frequency=12))

# Yearly sum
as.year <- function(x) as.numeric(floor(as.yearmon(x)))
yearsum <- as.ts(aggregate(z_test, as.year, sum))

..however, what is the best way to return the sum of specific months using aggregate? For example I would like to have the sum of July and August for each year (similar shape as yearsum)

JulAug_sum <-?

Body:
Hope this helps

library(zoo)

# Test dataset
ts_test <-  as.zoo(ts(rnorm(200), start=c(1922,1), frequency=12))

# Yearly sum
as.year <- function(x) as.numeric(floor(as.yearmon(x)))
yearsum <- as.ts(aggregate(as.zoo(ts_test), as.year, sum))

df <- subset(ts_test, (cycle(ts_test) == 7 | cycle(ts_test) == 8))
JulAugsum <- as.ts(aggregate(as.zoo(df), as.year, sum))


问:
When i ionic app build at that time build is successful but when i emulate with android at that time give following error
When i ionic app build at that time build is successful but when i emulate with android at that time give following error

```<code>D:/Demo-Projects/tabsapp/platforms/android/build/outputs/apk/android-debug.apk:
1 file pushed. 1.2 MB/s (4213012 bytes in 3.437s)

        pkg: /data/local/tmp/android-debug.apk enter code here

Failure [INSTALL_FAILED_OLDER_SDK]

rm failed for -f, Read-only file system

**[ERROR] An error occurred while running cordova emulate android (exit code 1).**
</code>```

advance thanks a lot please help me i am stuck here.

答:
This problem Solved using the declaration of Sdk Version in AndroidManifest.xml file and also to be noted that in SDK install api in SDK tool which version of declare in android:minSdkVersion.

```<code><uses-sdk android:minSdkVersion="16" android:targetSdkVersion="26" />
</code>```

Body:
When i ionic app build at that time build is successful but when i emulate with android at that time give following error

D:/Demo-Projects/tabsapp/platforms/android/build/outputs/apk/android-debug.apk:
1 file pushed. 1.2 MB/s (4213012 bytes in 3.437s)

        pkg: /data/local/tmp/android-debug.apk enter code here

Failure [INSTALL_FAILED_OLDER_SDK]

rm failed for -f, Read-only file system

**[ERROR] An error occurred while running cordova emulate android (exit code 1).**

advance thanks a lot please help me i am stuck here.

Body:
This problem Solved using the declaration of Sdk Version in AndroidManifest.xml file and also to be noted that in SDK install api in SDK tool which version of declare in android:minSdkVersion.

<uses-sdk android:minSdkVersion="16" android:targetSdkVersion="26" />


答:
"I'm taking data that I need to take into this algorithm from MySQL,
  and JavaScript just can't do this".

An AJAX request from the JavaScript in your browser to a PHP script on your server is the straightforward solution to this.

To summarise the process: In the request, the JavaScript code sends some relevant parameters about what it wants, PHP receives that data, queries the database, and returns the results in the response to the AJAX request. JavaScript receives this response, reads the data and continues its processing.

Node.js is just another server-side scripting framework, analagous to PHP. Don't let the fact it uses JavaScript as its programming language confuse you. There is absolutely no need to use Node in this scenario, if your existing server-side solution is written in PHP.

Browser-based JS and PHP can communicate with each other very happily using normal HTTP requests (likely initiated via AJAX, so you avoid page refreshes etc). That's the beauty of the web. The client and server can use totally different programming languages and different operating systems, and it makes no difference at all because they simply exchange data using a common protocol (HTTP) which both can understand.

Title: Connecting PHP with node.js/javascript

Body:
I have to implement knapsack problem algorithm on my site that's based on PHP. I Thought that I will make it in JavaScript and I have ran into a problem. I'm taking data that I need to take into this algorithm from MySQL, and JavaScript just can't do this. So I managed to do this by adding connector from Node.js. The algorithm works when user is giving some input. I made an form in HTML just to grab input and use it as parameter in my function. The problem is now that whole website is wrote in PHP and I can't connect it with JavaScript, because of node.js part where I'm connecting to database. I want to ask if there is any way to use this.

To sum it up and make it clear:
website is in PHP, I want to make a simple HTML form to grab input from user into parameter function from JavaScript file. Problem is that my JavaScript file needs MySQL data to run so it becomes node.js. And from what I know it's not that easy to run node.js on PHP based webserver. Is it possible to combine PHP with JavaScript so PHP will load data from MySQL into JavaScript? What you guys suggest?


问:
What are global states? How do they affect testability and how to avoid them?
List down the various global states like global variable, singleton object etc.,

I read that they affect the testability of code. Can you explain alternatives to global states that help in improving the testability of the code?

答:
Global variables and singletons are so similar from the testability viewpoint that they don’t have to be treated separately. Good OO design should be like bricks of Lego that fit together to create the resulting system. The main problem with globals is that you lose isolation. When you access your collaborators using globals or singletons, the classes are no longer separate bricks that you can easily take and reorganize, use in isolation or reuse in another project. When you take some class that depends on globals, you drag the rest of the design with it. In testing this makes problems because you have to take extra steps to cut the connections from your class to its collaborators, so that you can test it in isolation. (I’ve written more about this on my blog.)

A nice solution to the problem is supplying the class dependencies from the outside. You simply introduce some kind of mechanism (maybe a simple class) that will take all the isolated bricks and connect them into the object graph that makes up your application. This is what Inversion of Control and Dependency Injection is all about.


问:
Django Model: Meta: how to have default ordering case-insensitive
I am having a Django Model as shown below: I know that we can set the default ordering in the Meta class.

```<code>class Ingredient(models.Model):
    name = models.CharField(max_length=200,unique=True,null=False)
    slug = models.SlugField(unique=True)

    class Meta:
        ordering = ["name"]
</code>```

As the ordering is set to name here. What i found is, it is ordering by case-sensitive. So how to make it case-insensitive

答:
It's not possible set the default order to case-insensitive in the model meta options (source).

What you can do is use the order_by method of the QuerySet of your model:

```<code>from django.db.models.functions import Lower

Ingredient.objects.order_by(Lower('name'))
</code>```

As stated already in this answer

To be able to have it as a default ordering (and avoid repeating the order_by method on each one of your querysets), you might want to create a custom Manager class for your Ingredient model:

```<code># managers.py
from django.db.models.functions import Lower

class OrderedIngredientManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().order_by(Lower('name'))

# models.py
from .managers import OrderedIngredientManager

class Ingredient(models.Model):
    name = models.CharField(max_length=200,unique=True,null=False)
    slug = models.SlugField(unique=True)

    ordered_objects = OrderedIngredientManager()
</code>```

So you can have all your QuerySet ordered:

```<code>Ingredient.ordered_objects.all()
</code>```

Body:
I am having a Django Model as shown below: I know that we can set the default ordering in the Meta class.

class Ingredient(models.Model):
    name = models.CharField(max_length=200,unique=True,null=False)
    slug = models.SlugField(unique=True)

    class Meta:
        ordering = ["name"]

As the ordering is set to name here. What i found is, it is ordering by case-sensitive. So how to make it case-insensitive

Body:
It's not possible set the default order to case-insensitive in the model meta options (source).

What you can do is use the order_by method of the QuerySet of your model:

from django.db.models.functions import Lower

Ingredient.objects.order_by(Lower('name'))

As stated already in this answer

To be able to have it as a default ordering (and avoid repeating the order_by method on each one of your querysets), you might want to create a custom Manager class for your Ingredient model:

# managers.py
from django.db.models.functions import Lower

class OrderedIngredientManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().order_by(Lower('name'))

# models.py
from .managers import OrderedIngredientManager

class Ingredient(models.Model):
    name = models.CharField(max_length=200,unique=True,null=False)
    slug = models.SlugField(unique=True)

    ordered_objects = OrderedIngredientManager()

So you can have all your QuerySet ordered:

Ingredient.ordered_objects.all()


问:
unexpected response code 401 for URL
```<code>package com.example.murarilal.volley;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    RequestQueue queue;
    ListView listView;
    List<Hero> heroList;

    private String url="API_KEY";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         queue= Volley.newRequestQueue(this);
        home();

        listView = (ListView) findViewById(R.id.listView);
        heroList = new ArrayList<>();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                Intent intent=new Intent(getApplicationContext(),ArticleActivity.class);
                intent.putExtra("description",url);
                startActivity(intent);
            }
        });
    }

    public void home()
    {
        JsonObjectRequest request =new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                try {
                    JSONObject obj = new JSONObject(String.valueOf(response));

                    JSONArray array = obj.getJSONArray("articles");

                    for (int i = 0; i < array.length(); i++) {
                        Hero hero=new Hero( (String) array.getJSONObject(i).get("title"),(String) array.getJSONObject(i).get("urlToImage"));
                        heroList.add(hero);
                    }

                    ListViewAdapter adapter = new ListViewAdapter(heroList, getApplicationContext());
                    listView.setAdapter(adapter);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
                , new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        queue.add(request);
    }
}

package com.example.murarilal.volley;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class ArticleActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_article);
        String url="https://newsapi.org/v1/articles?source=techcrunch&apiKey=59b308aec9f242fe98b527ab9ba93199";

        WebView webView=(WebView)findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());

        Intent intent=getIntent();
        webView.loadDataWithBaseURL(url,null,intent.getStringExtra("description"),"text/html","UTF-8");
        webView.loadUrl(url);
    }
}
</code>```

https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=d6eaad863cc640a7a6864d18196bea9e

I'm trying to fetch data from the above url but it returns an unexpected 401 response code. I checked the url and it's perfectly valid but the my code gives this error. when the emulator starts it shows blank activity

this the log error

11-17 16:20:20.804 14350-14350/com.example.murarilal.volley
  W/System.err: com.android.volley.AuthFailureError 11-17 16:20:20.804
  14350-14350/com.example.murarilal.volley W/System.err:     at
  com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:141)
  11-17 16:20:20.804 14350-14350/com.example.murarilal.volley
  W/System.err:     at
  com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:105)

答:
I tried both api V1 And V2 with volley and got status code 200 and the data matches with the data shown when the request is made from a browser.

To help Can you add Logs and post it over here

```<code>  , new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
             Log.d(TAG,error.networkResponse.toString());
             error.printStackTrace();
        }
    });
</code>```

Title: unexpected response code 401 for URL

Body:
package com.example.murarilal.volley;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    RequestQueue queue;
    ListView listView;
    List<Hero> heroList;

    private String url="API_KEY";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         queue= Volley.newRequestQueue(this);
        home();

        listView = (ListView) findViewById(R.id.listView);
        heroList = new ArrayList<>();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                Intent intent=new Intent(getApplicationContext(),ArticleActivity.class);
                intent.putExtra("description",url);
                startActivity(intent);
            }
        });
    }

    public void home()
    {
        JsonObjectRequest request =new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                try {
                    JSONObject obj = new JSONObject(String.valueOf(response));

                    JSONArray array = obj.getJSONArray("articles");

                    for (int i = 0; i < array.length(); i++) {
                        Hero hero=new Hero( (String) array.getJSONObject(i).get("title"),(String) array.getJSONObject(i).get("urlToImage"));
                        heroList.add(hero);
                    }

                    ListViewAdapter adapter = new ListViewAdapter(heroList, getApplicationContext());
                    listView.setAdapter(adapter);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
                , new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        queue.add(request);
    }
}

package com.example.murarilal.volley;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class ArticleActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_article);
        String url="https://newsapi.org/v1/articles?source=techcrunch&apiKey=59b308aec9f242fe98b527ab9ba93199";

        WebView webView=(WebView)findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());

        Intent intent=getIntent();
        webView.loadDataWithBaseURL(url,null,intent.getStringExtra("description"),"text/html","UTF-8");
        webView.loadUrl(url);
    }
}

https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=d6eaad863cc640a7a6864d18196bea9e

I'm trying to fetch data from the above url but it returns an unexpected 401 response code. I checked the url and it's perfectly valid but the my code gives this error. when the emulator starts it shows blank activity

this the log error

11-17 16:20:20.804 14350-14350/com.example.murarilal.volley
  W/System.err: com.android.volley.AuthFailureError 11-17 16:20:20.804
  14350-14350/com.example.murarilal.volley W/System.err:     at
  com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:141)
  11-17 16:20:20.804 14350-14350/com.example.murarilal.volley
  W/System.err:     at
  com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:105)

Body:
I tried both api V1 And V2 with volley and got status code 200 and the data matches with the data shown when the request is made from a browser.

To help Can you add Logs and post it over here

  , new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
             Log.d(TAG,error.networkResponse.toString());
             error.printStackTrace();
        }
    });


问:
SQL Server RowNumbering
```<code>SrNo   TextCol
--------------
NULL   ABC
NULL   ABC
NULL   ASC
NULL   qwe
</code>```

I want to update the SrNo column with numbers 1,2,3,4 without changing sequence of other columns.

答:
Tables are unordered, so you cannot rely on "existing sequence". However a "trick" is to use select null which in effect does nothing to the row order. While it works you should not rely on it as a permanent solution.

```<code>WITH cte AS (
        SELECT SrNo, TextCol
            , ROW_NUMBER() OVER (ORDER BY (select NULL)) rn
        FROM yourTable
     )
UPDATE cte
SET SrNo = rn;
</code>```

Title: SQL Server RowNumbering

Body:
SrNo   TextCol
--------------
NULL   ABC
NULL   ABC
NULL   ASC
NULL   qwe

I want to update the SrNo column with numbers 1,2,3,4 without changing sequence of other columns.

Body:
Tables are unordered, so you cannot rely on "existing sequence". However a "trick" is to use select null which in effect does nothing to the row order. While it works you should not rely on it as a permanent solution.

WITH cte AS (
        SELECT SrNo, TextCol
            , ROW_NUMBER() OVER (ORDER BY (select NULL)) rn
        FROM yourTable
     )
UPDATE cte
SET SrNo = rn;