答: if x is numeric, then add scale_x_continuous(); if x is character/factor, then add scale_x_discrete(). This might solve your problem.

Title: Plotting with ggplot2: "Error: Discrete value supplied to continuous scale" on categorical y-axis

Body:
The plotting code below gives Error: Discrete value supplied to continuous scale

What's wrong with this code? It works fine until I try to change the scale so the error is there... I tried to figure out solutions from similar problem but couldn't.

meltDF <- data.frame(
  MW = c(
    3.9, 6.4, 7.4, 8.1, 9, 9.4, 3.9, 6.4, 7.4, 8.1, 9, 9.4, 3.9, 6.4, 7.4, 8.1, 9,
    9.4, 3.9, 6.4, 7.4, 8.1, 9, 9.4, 3.9, 6.4, 7.4, 8.1, 9, 9.4, 3.9, 6.4, 7.4,
    8.1, 9, 9.4, 3.9, 6.4, 7.4, 8.1, 9, 9.4, 3.9, 6.4, 7.4, 8.1, 9, 9.4, 3.9, 6.4,
    7.4, 8.1, 9, 9.4, 3.9, 6.4, 7.4, 8.1, 9, 9.4, 3.9, 6.4, 7.4, 8.1, 9, 9.4, 3.9,
    6.4, 7.4, 8.1, 9, 9.4, 3.9, 6.4, 7.4, 8.1, 9, 9.4, 3.9, 6.4, 7.4, 8.1, 9, 9.4,
    3.9, 6.4, 7.4, 8.1, 9, 9.4, 3.9, 6.4, 7.4, 8.1, 9, 9.4, 3.9, 6.4, 7.4, 8.1, 9,
    9.4, 3.9, 6.4, 7.4, 8.1, 9, 9.4, 3.9, 6.4, 7.4, 8.1, 9, 9.4, 3.9, 6.4, 7.4,
    8.1, 9, 9.4
  ),
  variable = factor(
    c(
      "10", "10", "10", "10", "10", "10", "33.95", "33.95", "33.95",
      "33.95", "33.95", "33.95", "58.66", "58.66", "58.66", "58.66",
      "58.66", "58.66", "84.42", "84.42", "84.42", "84.42", "84.42",
      "84.42", "110.21", "110.21", "110.21", "110.21", "110.21", "110.21",
      "134.16", "134.16", "134.16", "134.16", "134.16", "134.16", "164.69",
      "164.69", "164.69", "164.69", "164.69", "164.69", "199.1", "199.1",
      "199.1", "199.1", "199.1", "199.1", "234.35", "234.35", "234.35",
      "234.35", "234.35", "234.35", "257.19", "257.19", "257.19", "257.19",
      "257.19", "257.19", "361.84", "361.84", "361.84", "361.84", "361.84",
      "361.84", "432.74", "432.74", "432.74", "432.74", "432.74", "432.74",
      "506.34", "506.34", "506.34", "506.34", "506.34", "506.34", "581.46",
      "581.46", "581.46", "581.46", "581.46", "581.46", "651.71", "651.71",
      "651.71", "651.71", "651.71", "651.71", "732.59", "732.59", "732.59",
      "732.59", "732.59", "732.59", "817.56", "817.56", "817.56", "817.56",
      "817.56", "817.56", "896.24", "896.24", "896.24", "896.24", "896.24",
      "896.24", "971.77", "971.77", "971.77", "971.77", "971.77", "971.77",
      "1038.91", "1038.91", "1038.91", "1038.91", "1038.91", "1038.91"
    ),
    levels = c(
      "10", "33.95", "58.66", "84.42", "110.21", "134.16", "164.69",
      "199.1", "234.35", "257.19", "361.84", "432.74", "506.34", "581.46",
      "651.71", "732.59", "817.56", "896.24", "971.77", "1038.91"
    )
  ),
  value = c(
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0
  )
)

The plotting code:

## Plotting
ggplot(meltDF[meltDF$value == 1,]) + geom_point(aes(x = MW, y = variable)) +
  scale_x_continuous(limits=c(0, 1200), breaks=c(0, 400, 800, 1200)) +
  scale_y_continuous(limits=c(0, 1200), breaks=c(0, 400, 800, 1200))

Here's how the plot looked before adding scale:


来源: stackexchange

问:
URL Rewrite on IIS from http to https is not working,
I have a problem. On IIS I got a web-site with two ports 80 and 443(https). I want to redirect all the http requests from user to https. I also added Rewrite rule to https, but when I enter in browser http://localhost/site it gives me the same page. I need to redirect user to httpS://localhost/site.

Maybe this is because of my local configurations?

And I disable Require SSL on IIS.

```<code>The rule is:
<rewrite>
  <rules>
    <rule name="HTTPS Redirect">
      <match url="(.*)" ignoreCase="false" />
      <conditions>
        <add input="{HTTPS}" pattern="off" ignoreCase="false" />
      </conditions>
      <action type="Redirect" redirectType="Found" url="https://{HTTP_HOST}{REQUEST_URI}" />
    </rule>
  </rules>
</rewrite>
</code>```

Thank you.

答:
Also, if you have more than one rule, order could matter.  Be sure to add the redirect rule before other rules or redirect may not fire.

Here is an example that is using SPA that required the rule order.

```<code> <rules>

         // Adding this as last rule will cause it to not redirect
        <rule name="HTTP/S to HTTPS Redirect" enabled="true" stopProcessing="true">
        <match url="(.*)" />
        <conditions logicalGrouping="MatchAny">
          <add input="{SERVER_PORT_SECURE}" pattern="^0$" />
        </conditions>
        <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" />
        </rule>

      <rule name="static dist files" stopProcessing="true">
        <match url="^(.+)" />
        <conditions>
          <add input="{APPL_PHYSICAL_PATH}app\{R:1}" matchType="IsFile" />
        </conditions>
        <action type="Rewrite" url="/app/{R:1}" />
      </rule>
      <rule name="index.html as document root" stopProcessing="true">
        <match url="^$" />
        <action type="Rewrite" url="/app/" />
      </rule>
      <rule name="SPA Routes" stopProcessing="true">
        <match url=".*|.*/.*$" />
        <conditions logicalGrouping="MatchAll">
          <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
        </conditions>
        <action type="Rewrite" url="/app/" />
      </rule>
    </rules>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a problem. On IIS I got a web-site with two ports 80 and 443(https). I want to redirect all the http requests from user to https. I also added Rewrite rule to https, but when I enter in browser http://localhost/site it gives me the same page. I need to redirect user to httpS://localhost/site.

Maybe this is because of my local configurations?

And I disable Require SSL on IIS.

The rule is:
<rewrite>
  <rules>
    <rule name="HTTPS Redirect">
      <match url="(.*)" ignoreCase="false" />
      <conditions>
        <add input="{HTTPS}" pattern="off" ignoreCase="false" />
      </conditions>
      <action type="Redirect" redirectType="Found" url="https://{HTTP_HOST}{REQUEST_URI}" />
    </rule>
  </rules>
</rewrite>

Thank you.

Body:
Also, if you have more than one rule, order could matter.  Be sure to add the redirect rule before other rules or redirect may not fire.

Here is an example that is using SPA that required the rule order.

 <rules>

         // Adding this as last rule will cause it to not redirect
        <rule name="HTTP/S to HTTPS Redirect" enabled="true" stopProcessing="true">
        <match url="(.*)" />
        <conditions logicalGrouping="MatchAny">
          <add input="{SERVER_PORT_SECURE}" pattern="^0$" />
        </conditions>
        <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" />
        </rule>

      <rule name="static dist files" stopProcessing="true">
        <match url="^(.+)" />
        <conditions>
          <add input="{APPL_PHYSICAL_PATH}app\{R:1}" matchType="IsFile" />
        </conditions>
        <action type="Rewrite" url="/app/{R:1}" />
      </rule>
      <rule name="index.html as document root" stopProcessing="true">
        <match url="^$" />
        <action type="Rewrite" url="/app/" />
      </rule>
      <rule name="SPA Routes" stopProcessing="true">
        <match url=".*|.*/.*$" />
        <conditions logicalGrouping="MatchAll">
          <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
        </conditions>
        <action type="Rewrite" url="/app/" />
      </rule>
    </rules>


问:
Bootstrap not being applied to dynamically created elements
I'm attempting to make a calculator where you have the possibility to increase the number of inputs if you so wish to - the calculator itself works fine in finding the necessary values, however I wish to also have the possibility to search through the dropdown inputs as they do get quite lengthy, hence why I am using bootstrap-select.

The problem is that only the default inputs get the bootstrap theme applied to them, whereas the inputs created by clicking on the necessary button don't get the theme applied. How do I go about fixing this?

What do you expect? All inputs to be 'stylised' like the default one, with the search menu etc.
What do you get? Only the default input is 'stylised', whereas the ones created by clicking on the button don't

var i = 0;

function createGear() {
    i++;

    var container = document.getElementById("newGear");

    var gear = document.createElement("select");
    gear.id = "gear" + i;
    gear.setAttribute("class", "selectpicker");
    gear.setAttribute("data-live-search", "true");
    container.appendChild(gear);

    var none = document.createElement("option");
    none.value = "none";
    none.text = "";
    gear.add(none);

    var pistols = document.createElement("optgroup");
    pistols.label = "Pistols";
    gear.add(pistols);

    var pistol1 = document.createElement("option");
    pistol1.value = "pistol1";
    pistol1.text = "M1911";
    gear.add(pistol1);
    pistols.appendChild(pistol1);

    return i;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.min.css" />
    <script src="js/script.js" type="text/javascript"></script>
</head>

<body>
    <form id="form">
        <select class="selectpicker" data-live-search="true" id="gear0">
                <option></option>
                <optgroup label="Pistols">
                    <option value="pistol1">M1911</option>
                </optgroup>
                </select>
        <div id="newGear">

        </div>
        <input type="button" onclick="createGear()" value="Create Gear Input!">
    </form>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/js/bootstrap-select.min.js"></script>

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

答:
That is because the select that you dynamically add to the page are never initialised as bootstrap-select components. The one that you've already got on the page is automatically initialised as such when the page loads because it has the selectpicker class.

You just need to add this statement after you add the new select to the page:

```<code>$(gear).selectpicker();
</code>```

Body:
I'm attempting to make a calculator where you have the possibility to increase the number of inputs if you so wish to - the calculator itself works fine in finding the necessary values, however I wish to also have the possibility to search through the dropdown inputs as they do get quite lengthy, hence why I am using bootstrap-select.

The problem is that only the default inputs get the bootstrap theme applied to them, whereas the inputs created by clicking on the necessary button don't get the theme applied. How do I go about fixing this?

What do you expect? All inputs to be 'stylised' like the default one, with the search menu etc.
What do you get? Only the default input is 'stylised', whereas the ones created by clicking on the button don't

var i = 0;

function createGear() {
    i++;

    var container = document.getElementById("newGear");

    var gear = document.createElement("select");
    gear.id = "gear" + i;
    gear.setAttribute("class", "selectpicker");
    gear.setAttribute("data-live-search", "true");
    container.appendChild(gear);

    var none = document.createElement("option");
    none.value = "none";
    none.text = "";
    gear.add(none);

    var pistols = document.createElement("optgroup");
    pistols.label = "Pistols";
    gear.add(pistols);

    var pistol1 = document.createElement("option");
    pistol1.value = "pistol1";
    pistol1.text = "M1911";
    gear.add(pistol1);
    pistols.appendChild(pistol1);

    return i;
}

<!DOCTYPE html>

    <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.min.css" />

    <form id="form">
        <select class="selectpicker" data-live-search="true" id="gear0">
                <option></option>
                <optgroup label="Pistols">
                    <option value="pistol1">M1911</option>
                </optgroup>
                </select>

        <input type="button" onclick="createGear()" value="Create Gear Input!">
    </form>

Body:
That is because the select that you dynamically add to the page are never initialised as bootstrap-select components. The one that you've already got on the page is automatically initialised as such when the page loads because it has the selectpicker class.

You just need to add this statement after you add the new select to the page:

$(gear).selectpicker();


问:
Simple check for SELECT query empty result
Can anyone point out how to check if a select query returns non empty result set?

For example I have next query:

```<code>SELECT * FROM service s WHERE s.service_id = ?;
</code>```

Should I do something like next:

```<code>ISNULL(SELECT * FROM service s WHERE s.service_id = ?)
</code>```

to test if result set is not empty?

答:
You can do it in a number of ways.

```<code>IF EXISTS(select * from ....)
begin
 -- select * from ....
end
else
 -- do something
</code>```

Or you can use IF NOT EXISTS , @@ROW_COUNT like

```<code>select * from ....
IF(@@ROW_COUNT>0)
begin
-- do something
end
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Can anyone point out how to check if a select query returns non empty result set?

For example I have next query:

SELECT * FROM service s WHERE s.service_id = ?;

Should I do something like next:

ISNULL(SELECT * FROM service s WHERE s.service_id = ?)

to test if result set is not empty?

Body:
You can do it in a number of ways.

IF EXISTS(select * from ....)
begin
 -- select * from ....
end
else
 -- do something

Or you can use IF NOT EXISTS , @@ROW_COUNT like

select * from ....
IF(@@ROW_COUNT>0)
begin
-- do something
end


问:
Why is this transition not working? (jQuery toggle + css)
Transitions are gone when toggling class? I wanted to add HTML as well, but stackoverflow kept saying that my question was mostly code and would not let me save, that is why I added codepen link, which is working fine now, I have just edited it.

https://codepen.io/anon/pen/pdmpNE

```<code>    <div class="container">
  <div class="row">
    <div class="col bg-primary one">
      <h1>some text</h1>
    </div>
    <div class="col bg-danger two">
      <h1>hidden text</h1>
    </div>
  </div>
</div>

.two {
  visibility: hidden;
  display: none;
  opacity: 0;
  transition: all 1s ease-out;
}

.is-visible {
      display: block;
            visibility: visible;
            opacity: 1;
            transition: all 1s ease-out;
}

$('.row').click(function(){
    $(this).children('.two').toggleClass('is-visible');
});
</code>```

答:
I think I pieced together what you were looking for, but please next time format your question with all code. Also, if you're going to add a Codepen, make sure to actually add your CSS and JS if you're going to include some.

What I changed is that I added your .two class to your second div and made your $('.row).click() function once the document is ready.

Here's the HTML:

```<code><div class="col bg-danger two">
  <h1>hidden text</h1>
</div>
</code>```

Here's the JS:

```<code>$('document').ready(function() {
  $('.row').click(function(){
    $(this).children('.two').toggleClass('is-visible');
  });
});
</code>```

Here's the Codepen displaying the changes.

Body:
Transitions are gone when toggling class? I wanted to add HTML as well, but stackoverflow kept saying that my question was mostly code and would not let me save, that is why I added codepen link, which is working fine now, I have just edited it.

https://codepen.io/anon/pen/pdmpNE

some text

hidden text

.two {
  visibility: hidden;
  display: none;
  opacity: 0;
  transition: all 1s ease-out;
}

.is-visible {
      display: block;
            visibility: visible;
            opacity: 1;
            transition: all 1s ease-out;
}

$('.row').click(function(){
    $(this).children('.two').toggleClass('is-visible');
});

Body:
I think I pieced together what you were looking for, but please next time format your question with all code. Also, if you're going to add a Codepen, make sure to actually add your CSS and JS if you're going to include some.

What I changed is that I added your .two class to your second div and made your $('.row).click() function once the document is ready.

Here's the HTML:

<div class="col bg-danger two">
  <h1>hidden text</h1>
</div>

Here's the JS:

$('document').ready(function() {
  $('.row').click(function(){
    $(this).children('.two').toggleClass('is-visible');
  });
});

Here's the Codepen displaying the changes.


问:
How to set Robots.txt or Apache to allow crawlers only at certain hours?
As traffic is distributed unevenly over 24 hours, I would like to disallow crawlers during peek hours and allow them at non-busy hours.

Is there a method to achieve this?

edit:
thanks for all the good advice.

This is another solution we found.

2bits.com has an article on setting IPTables firewall to limit the number of connections from certain IP addresses.

the article

the setting of IPTables:

Using connlimit

In newer Linux kernels, there is a connlimit module for iptables. It can be used like this:

iptables -I INPUT -p tcp -m connlimit --connlimit-above 5 -j REJECT

This limits connections from each IP address to no more than 5 simultaneous connections. This sort of "rations" connections, and prevents crawlers from hitting the site simultaneously.
*

答:
You can't control that in the robots.txt file. It's possible that some crawlers might support something like that, but none of the big ones do (as far as I know).

Dynamically changing the robots.txt file is also a bad idea in a case like this. Most crawlers cache the robots.txt file for a certain time, and continue using it until they refresh the cache. If they cache it at the "right" time, they might crawl normally all day. If they cache it at the "wrong" time, they would stop crawling altogether (and perhaps even remove indexed URLs from their index). For instance, Google generally caches the robots.txt file for a day, meaning that changes during the course of a day would not be visible to Googlebot.

If crawling is causing too much load on your server, you can sometimes adjust the crawl rate for individual crawlers. For instance, for Googlebot you can do this in Google Webmaster Tools.

Additionally, when crawlers attempt to crawl during times of high load, you can always just serve them a 503 HTTP result code. This tells crawlers to check back at some later time (you can also specify a retry-after HTTP header if you know when they should come back). While I'd try to avoid doing this strictly on a time-of-day basis (this can block many other features, such as Sitemaps, contextual ads, or website verification and can slow down crawling in general), in exceptional cases it might make sense to do that. For the long run, I'd strongly recommend only doing this when your server load is really much too high to successfully return content to crawlers.


问:
Loop with VBA Vlookup, with dynamic cell value
```<code>Sub tabelvul()

Dim nr(2)

For i = 2 To 31
    nr(1) = Range("AA" & i).Value
    nr(2) = Range("AN" & i).Value
    If nr(2) = 0 Then
        ' do nothing
    Else
        Range(nr(1)).Select
        ActiveCell.FormulaR1C1 = _
            "=VLOOKUP(nr(2),Tabel80[[Kolom1]:[Inschrijver]],2)"
    End If
Next i

End Sub
</code>```

The first value nr(1) has is B4, so i do get the formula of Vlookup in B4, however he is searching for nr(2) and not the corresponding value of nr(2), which is 1, so I want the formula to look for 1 in the table.

答: Maybe you should change "=VLOOKUP(nr(2),Tabel80[[Kolom1]:[Inschrijver]],2)" into "=VLOOKUP(" & nr(2) & ",Tabel80[[Kolom1]:[Inschrijver]],2)"

Body:
Sub tabelvul()

Dim nr(2)

For i = 2 To 31
    nr(1) = Range("AA" & i).Value
    nr(2) = Range("AN" & i).Value
    If nr(2) = 0 Then
        ' do nothing
    Else
        Range(nr(1)).Select
        ActiveCell.FormulaR1C1 = _
            "=VLOOKUP(nr(2),Tabel80[[Kolom1]:[Inschrijver]],2)"
    End If
Next i

End Sub

The first value nr(1) has is B4, so i do get the formula of Vlookup in B4, however he is searching for nr(2) and not the corresponding value of nr(2), which is 1, so I want the formula to look for 1 in the table.


问:
Can I make a Vbscript wait for scheduled shutdowns to occur?
I want to make a Vbscript wait until a scheduled shutdown occurs, Then launch a batch file to cancel it. I know enough to launch a batch from a vbs and how to cancel a shutdown but I need to know how to make a vbs that waits until shutdown occurs. (tell me if this is not possible)</p>

答:
A VBS file to start a hidden batch file.

```<code> CreateObject("WScript.Shell").Run """c:\windows\system32\cmd /c Mybat.bat""", 0, false
</code>```

The batch file cancelling a shutdown every 60 secs

```<code>:Loop
Shutdown /a
timeout /t 60
Goto Loop
</code>```

Body:
A VBS file to start a hidden batch file.

 CreateObject("WScript.Shell").Run """c:\windows\system32\cmd /c Mybat.bat""", 0, false

The batch file cancelling a shutdown every 60 secs

:Loop
Shutdown /a
timeout /t 60
Goto Loop


答:
var gearPrices= new Array();
gearPrices["none"]=0;
gearPrices["pistol1"]=25000;

var i = 0;

function createGear() {
    i++;

    var container = document.getElementById("newGear");
    container.setAttribute("class", "bootstrap-select");

    var gear = document.createElement("select");
    gear.id = "gear" + i;
    gear.setAttribute("class", "selectpicker");
    gear.setAttribute("data-live-search", "true");
    container.appendChild(gear);

    var none = document.createElement("option");
    none.value = "none";
    none.text = "";
    gear.add(none);

    var pistols = document.createElement("optgroup");
    pistols.label = "Pistols";
    gear.add(pistols);

    var pistol1 = document.createElement("option");
    pistol1.value = "pistol1";
    pistol1.text = "M1911";
    gear.add(pistol1);
    pistols.appendChild(pistol1);

    var amount = document.createElement("input");
    amount.id = "amount" + i;
    amount.type = "number";
    container.appendChild(amount);

  // The newly created element should be updated
  $(gear).selectpicker('refresh');

    return i;
}

function getGearPrice() {
    var price = 0, ix, ixLen, value, type;
    var newGear = document.getElementById('newGear');

    price += (gearPrices[document.getElementById('gear0').value || 'none']) *
             (document.getElementById('amount0').value || 0);

    var amountInputs = document.querySelectorAll("#newGear input[type='number']");
    var selectElements = document.querySelectorAll("#newGear select");

    for(ix = 0, ixLen = selectElements.length; ix < ixLen; ix++){
        type = selectElements[ix].value || 'none';
        value = amountInputs[ix].value || 0;
        price += gearPrices[type] * +value;
    }

    return price;
}

function getTotal() {
    var gearPrice = getGearPrice();

    document.getElementById('gearTotal').innerHTML = "Gear: £" + gearPrice;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
    <form id="form">
        <select class="selectpicker" data-live-search="true" id="gear0">
                <option></option>
                <optgroup label="Pistols">
                    <option value="pistol1">M1911</option>
                </optgroup>
                </select>
                <input type="text" id="amount0">
        <div id="newGear">

        </div>
        <input type="button" onclick="createGear()" value="Create Gear Input!">
        <input type="button" onClick="getTotal()">
    </form>
    <p id="gearTotal">
    Gear Total Over Here!
    </p>

    <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.min.css" />
    <link href="https://fonts.googleapis.com/css?family=Ubuntu" rel="stylesheet">
    <script src="js/script.js" type="text/javascript"></script>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>

  <script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/js/bootstrap-select.min.js"></script>
</body></code>```

Title: Bootstrap not being applied to dynamically created elements

Body:
var gearPrices= new Array();
gearPrices["none"]=0;
gearPrices["pistol1"]=25000;

var i = 0;

function createGear() {
    i++;

    var container = document.getElementById("newGear");
    container.setAttribute("class", "bootstrap-select");

    var gear = document.createElement("select");
    gear.id = "gear" + i;
    gear.setAttribute("class", "selectpicker");
    gear.setAttribute("data-live-search", "true");
    container.appendChild(gear);

    var none = document.createElement("option");
    none.value = "none";
    none.text = "";
    gear.add(none);

    var pistols = document.createElement("optgroup");
    pistols.label = "Pistols";
    gear.add(pistols);

    var pistol1 = document.createElement("option");
    pistol1.value = "pistol1";
    pistol1.text = "M1911";
    gear.add(pistol1);
    pistols.appendChild(pistol1);

    var amount = document.createElement("input");
    amount.id = "amount" + i;
    amount.type = "number";
    container.appendChild(amount);

  // The newly created element should be updated
  $(gear).selectpicker('refresh');

    return i;
}

function getGearPrice() {
    var price = 0, ix, ixLen, value, type;
    var newGear = document.getElementById('newGear');

    price += (gearPrices[document.getElementById('gear0').value || 'none']) *
             (document.getElementById('amount0').value || 0);

    var amountInputs = document.querySelectorAll("#newGear input[type='number']");
    var selectElements = document.querySelectorAll("#newGear select");

    for(ix = 0, ixLen = selectElements.length; ix < ixLen; ix++){
        type = selectElements[ix].value || 'none';
        value = amountInputs[ix].value || 0;
        price += gearPrices[type] * +value;
    }

    return price;
}

function getTotal() {
    var gearPrice = getGearPrice();

    document.getElementById('gearTotal').innerHTML = "Gear: £" + gearPrice;

}

<body>
    <form id="form">
        <select class="selectpicker" data-live-search="true" id="gear0">
                <option></option>
                <optgroup label="Pistols">
                    <option value="pistol1">M1911</option>
                </optgroup>
                </select>
                <input type="text" id="amount0">
        <div id="newGear">

        </div>
        <input type="button" onclick="createGear()" value="Create Gear Input!">
        <input type="button" onClick="getTotal()">
    </form>
    <p id="gearTotal">
    Gear Total Over Here!
    </p>

    <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.min.css" />
    <link href="https://fonts.googleapis.com/css?family=Ubuntu" rel="stylesheet">
    <script src="js/script.js" type="text/javascript"></script>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>

  <script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/js/bootstrap-select.min.js"></script>
</body>


答:
Please check if my solution is what you need. I add {$('#' + gear.id).selectpicker(); cause for dynamically generated you have to call bootstrap-select manually. I also wrapped it in setTimeout to allow browser to render everything properly: setTimeout(function () {$('#' + gear.id).selectpicker();}, 300).

var i = 0;

function createGear() {
    i++;

    var container = document.getElementById("newGear");

    var gear = document.createElement("select");
    gear.id = "gear" + i;
    gear.setAttribute("class", "selectpicker");
    gear.setAttribute("data-live-search", "true");
    container.appendChild(gear);
    setTimeout(function () {$('#' + gear.id).selectpicker();}, 300)

    var none = document.createElement("option");
    none.value = "none";
    none.text = "";
    gear.add(none);

    var pistols = document.createElement("optgroup");
    pistols.label = "Pistols";
    gear.add(pistols);

    var pistol1 = document.createElement("option");
    pistol1.value = "pistol1";
    pistol1.text = "M1911";
    gear.add(pistol1);
    pistols.appendChild(pistol1);

    return i;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.min.css" />
    <link href="https://fonts.googleapis.com/css?family=Ubuntu" rel="stylesheet">
    <script src="js/script.js" type="text/javascript"></script>
</head>

<body>
    <form id="form">
        <select class="selectpicker" data-live-search="true" id="gear0">
                <option></option>
                <optgroup label="Pistols">
                    <option value="pistol1">M1911</option>
                </optgroup>
                </select>
        <div id="newGear">

        </div>
        <input type="button" onclick="createGear()" value="Create Gear Input!">
    </form>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/js/bootstrap-select.min.js"></script>

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

Body:
Please check if my solution is what you need. I add {$('#' + gear.id).selectpicker(); cause for dynamically generated you have to call bootstrap-select manually. I also wrapped it in setTimeout to allow browser to render everything properly: setTimeout(function () {$('#' + gear.id).selectpicker();}, 300).

var i = 0;

function createGear() {
    i++;

    var container = document.getElementById("newGear");

    var gear = document.createElement("select");
    gear.id = "gear" + i;
    gear.setAttribute("class", "selectpicker");
    gear.setAttribute("data-live-search", "true");
    container.appendChild(gear);
    setTimeout(function () {$('#' + gear.id).selectpicker();}, 300)

    var none = document.createElement("option");
    none.value = "none";
    none.text = "";
    gear.add(none);

    var pistols = document.createElement("optgroup");
    pistols.label = "Pistols";
    gear.add(pistols);

    var pistol1 = document.createElement("option");
    pistol1.value = "pistol1";
    pistol1.text = "M1911";
    gear.add(pistol1);
    pistols.appendChild(pistol1);

    return i;
}

<!DOCTYPE html>
<html>
<head>
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.min.css" />
    <link href="https://fonts.googleapis.com/css?family=Ubuntu" rel="stylesheet">
    <script src="js/script.js" type="text/javascript"></script>
</head>

<body>
    <form id="form">
        <select class="selectpicker" data-live-search="true" id="gear0">
                <option></option>
                <optgroup label="Pistols">
                    <option value="pistol1">M1911</option>
                </optgroup>
                </select>
        <div id="newGear">

        </div>
        <input type="button" onclick="createGear()" value="Create Gear Input!">
    </form>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/js/bootstrap-select.min.js"></script>

</body>
</html>


问:
Run function in another file
I have this file to return address through geolocation:

```<code>import React, { Component } from 'react';
import axios from 'axios';

const __API_KEY__ = '&key=...';

export var address = '';

const getGeocode = () => {
  axios.get('https://maps.googleapis.com/maps/api/geocode/json?address='+ this.state.latitude +','+ this.state.longitude + __API_KEY__)
.then(response => {
  console.log(response);
    this.setState({
        place: response.data.results[0].formatted_address
    })
    address = response.data.results[0].formatted_address
  }).catch((error) => {
    this.setState({ error: error.message })
  });
};

export const getGeolocation = () => (
  navigator.geolocation.getCurrentPosition(
    (position) => {
      this.setState({
        latitude: position.coords.latitude,
        longitude: position.coords.longitude,
        error: null,
      }, () => this.getGeocode());
    },
    address = position.coords.latitude,
    (error) => this.setState({ error: error.message }),
    { enableHighAccuracy: true, timeout: 20000 },
  )
);
</code>```

I can return the address variable inside the other file where I need the address with:

```<code>import { Address } from './services/geolocation';
</code>```

But what happens is that the variable comes empty because it does not execute the code that takes the geolocation, how can I make the variable return the address?

[EDIT]

I tried to follow the advice of turning into a function with the return of the address and I got in this code:

```<code>import React, { Component } from 'react';
import axios from 'axios';

const __API_KEY__ = '&key=...';

function getGeocode( latitude, longitude ) {
  axios.get('https://maps.googleapis.com/maps/api/geocode/json?address='+ latitude +','+ longitude + __API_KEY__)
  .then(response => {
    console.log(response);
      var address = response.data.results[0].formatted_address
    }).catch((error) => {
      this.setState({ error: error.message })
    });

  return address;
};

export function getGeolocation() {
  navigator.geolocation.getCurrentPosition(
    (position) => {
      var address = getGeocode(position.coords.latitude, position.coords.longitude);
    },
    (error) => this.setState({ error: error.message }),
    { enableHighAccuracy: true, timeout: 20000 },
  )
  console.log(address);

  return address;
};
</code>```

And on the other I tried to import like this:

```<code>import { getGeolocation } from './services/geolocation';

const address = getGeolocation();
</code>```

But I got this error back:

```<code>(0,_geolocation.getGeolocation) is not a function
</code>```

答:
The easier way to do this is export a getAddress function instead of exporting the actual variable. So:

```<code>export function getAddress() { return address; }
</code>```

(or the arrow function equivalent if you prefer that syntax).

Title: Run function in another file

Body:
I have this file to return address through geolocation:

import React, { Component } from 'react';
import axios from 'axios';

const __API_KEY__ = '&key=...';

export var address = '';

const getGeocode = () => {
  axios.get('https://maps.googleapis.com/maps/api/geocode/json?address='+ this.state.latitude +','+ this.state.longitude + __API_KEY__)
.then(response => {
  console.log(response);
    this.setState({
        place: response.data.results[0].formatted_address
    })
    address = response.data.results[0].formatted_address
  }).catch((error) => {
    this.setState({ error: error.message })
  });
};

export const getGeolocation = () => (
  navigator.geolocation.getCurrentPosition(
    (position) => {
      this.setState({
        latitude: position.coords.latitude,
        longitude: position.coords.longitude,
        error: null,
      }, () => this.getGeocode());
    },
    address = position.coords.latitude,
    (error) => this.setState({ error: error.message }),
    { enableHighAccuracy: true, timeout: 20000 },
  )
);

I can return the address variable inside the other file where I need the address with:

import { Address } from './services/geolocation';

But what happens is that the variable comes empty because it does not execute the code that takes the geolocation, how can I make the variable return the address?

[EDIT]

I tried to follow the advice of turning into a function with the return of the address and I got in this code:

import React, { Component } from 'react';
import axios from 'axios';

const __API_KEY__ = '&key=...';

function getGeocode( latitude, longitude ) {
  axios.get('https://maps.googleapis.com/maps/api/geocode/json?address='+ latitude +','+ longitude + __API_KEY__)
  .then(response => {
    console.log(response);
      var address = response.data.results[0].formatted_address
    }).catch((error) => {
      this.setState({ error: error.message })
    });

  return address;
};

export function getGeolocation() {
  navigator.geolocation.getCurrentPosition(
    (position) => {
      var address = getGeocode(position.coords.latitude, position.coords.longitude);
    },
    (error) => this.setState({ error: error.message }),
    { enableHighAccuracy: true, timeout: 20000 },
  )
  console.log(address);

  return address;
};

And on the other I tried to import like this:

import { getGeolocation } from './services/geolocation';

const address = getGeolocation();

But I got this error back:

(0,_geolocation.getGeolocation) is not a function

Body:
The easier way to do this is export a getAddress function instead of exporting the actual variable. So:

export function getAddress() { return address; }

(or the arrow function equivalent if you prefer that syntax).


问:
Visual Studio Javascript extensions feature comparison
I know I'm not the first one that would like to have #region and brace matching support for Javascript. That's why I don't want to install one by one and see which one behaves better and which functionality it supports.

I would like to ask other fellow developers to provide feature comparison for these Visual Studio 2010 Javascript extensions:

JSEnhancements

Visual Studio 2010 JavaScript Outlining

JScript Editor Extensions

And any issues you might've had with them. JSEnhancements seems to have the most downloads, but that still doesn't give me any ideas of its features compared to others.

It's great that Microsoft provides some sort of integrated extension propagation and management, but there's an overwhelming amount of them and it's really hard to choose the right ones.

Other Javascript VS tools

There are other tools as well that some of you may be using. If you find any of those particularly useful, please provide some information and I'll add it here to this list. It may help us lots.

Javascript Parser - parses Javascript file and displays a tree structure of the code (closures/functions/...)

答:
Well there is one more tool for javascript "Javascript parser" which will parse your files and make a map on it. It is good but for me working with jquery it didn't help much.

Among the rest of the tools you mentioned, I was working too with JSenhancements for some time but I have switched to JScript Editor Extensions which I can tell seems more promising (highlight of current word, para comments etc).

It hasn't crashed since.


答:
I'm pretty sure there are other things that could be improved in your code, but you should change:

```<code>"=VLOOKUP(nr(2),Tabel80[[Kolom1]:[Inschrijver]],2)"
</code>```

To this:

```<code>"=VLOOKUP(" & nr(2) & ",Tabel80[[Kolom1]:[Inschrijver]],2)"
</code>```

Well it looks like you are wanting to enter the Vlookup on a range until nr(2) = Range("AN" & i).value = 0, so I don't know why you would use an array at all, if I knew what you were trying with more detail, could probably make it even better, but with what I know, this could do:

```<code>Sub tabelvul()
For i = 2 To 31
    If Range("AN" & i).Value = 0 Then
        ' do nothing
    Else
        Range("AA" & i).FormulaR1C1 = _
            "=VLOOKUP(" & Range("AN" & i).Value & ",Tabel80[[Kolom1]:[Inschrijver]],2)"
    End If
Next i
End Sub
</code>```

Title: Loop with VBA Vlookup, with dynamic cell value

Body:
I'm pretty sure there are other things that could be improved in your code, but you should change:

"=VLOOKUP(nr(2),Tabel80[[Kolom1]:[Inschrijver]],2)"

To this:

"=VLOOKUP(" & nr(2) & ",Tabel80[[Kolom1]:[Inschrijver]],2)"

Well it looks like you are wanting to enter the Vlookup on a range until nr(2) = Range("AN" & i).value = 0, so I don't know why you would use an array at all, if I knew what you were trying with more detail, could probably make it even better, but with what I know, this could do:

Sub tabelvul()
For i = 2 To 31
    If Range("AN" & i).Value = 0 Then
        ' do nothing
    Else
        Range("AA" & i).FormulaR1C1 = _
            "=VLOOKUP(" & Range("AN" & i).Value & ",Tabel80[[Kolom1]:[Inschrijver]],2)"
    End If
Next i
End Sub


问:
Python Function Returning List Objects Out of Order
I'm relatively new to the Python language.  I'm aware of most of the basic functionality & theory, all the different classes of object and their behavior/properties etc.

Anyway, I was writing basic functions to explore different concepts in practice and get to know the language more intuitively.  One in particular has left me vexed!  Can anyone share any insight into why this result is not as expected?

Here is the code I ran:

```<code>test_list = [2, 4, 6]
def test_func(k):
    global x, y, z
    for n in k:
        k[k.index(n)] = n * 2
    x, y, z = k
    return k
test_func(test_list)
print(test_list)
print(x)
print(y)
print(z)
</code>```

I would have expected the result to be:

```<code>[4, 8, 12]
4
8
12
</code>```

However, the actual result is as follows:

```<code>[8, 4, 12]
8
4
12
</code>```

It seems that the first two items of the list have been swapped.

I can't see what could be causing this?  If anyone can see what's happening here, please share the insight!

Thanks,
Oscar South

答:
In the first iteration the first element is changed to 4. In the second iteration the index of 4 is 0 not 1 as you expect.
Try this:</p>

```<code>test_list = [2, 4, 6]
def test_func(k):
    global x, y, z
    l = list()
    for n in k:
        print(n, k.index(n))
        l.append(n * 2)
    x, y, z = l
    return l
test_func(test_list)
print(test_list)
print(x)
print(y)
print(z)
</code>```

Body:
I'm relatively new to the Python language.  I'm aware of most of the basic functionality & theory, all the different classes of object and their behavior/properties etc.

Anyway, I was writing basic functions to explore different concepts in practice and get to know the language more intuitively.  One in particular has left me vexed!  Can anyone share any insight into why this result is not as expected?

Here is the code I ran:

test_list = [2, 4, 6]
def test_func(k):
    global x, y, z
    for n in k:
        k[k.index(n)] = n * 2
    x, y, z = k
    return k
test_func(test_list)
print(test_list)
print(x)
print(y)
print(z)

I would have expected the result to be:

[4, 8, 12]
4
8
12

However, the actual result is as follows:

[8, 4, 12]
8
4
12

It seems that the first two items of the list have been swapped.

I can't see what could be causing this?  If anyone can see what's happening here, please share the insight!

Thanks,
Oscar South

Body:
In the first iteration the first element is changed to 4. In the second iteration the index of 4 is 0 not 1 as you expect.
Try this:

test_list = [2, 4, 6]
def test_func(k):
    global x, y, z
    l = list()
    for n in k:
        print(n, k.index(n))
        l.append(n * 2)
    x, y, z = l
    return l
test_func(test_list)
print(test_list)
print(x)
print(y)
print(z)


问:
How to change the font size of a class to make it responsive using Bootstrap4 with sass?
So, i'm working on a project using Bootstrap 4 sass and i want to make the font-size of the h3 to be responsive.

When i go to the _type.scss, the h3 property looks like this:

```<code>h3, .h3 { font-size: $h3-font-size; }
</code>```

it's calling the variable $h3-font-size from _variables.scss that looks like this:
    $h3-font-size:                $font-size-base * 1.75 !default;

the $font-size-base variable looks like this:

```<code>$font-size-base:              1rem !default;
</code>```

So, this far i know that the font-size of the h3 class is 1.75rem, what i want is that font-size to be 1.5rem from xs to md, and to be 1.75rem from md to lg.

i went to the Bootstrap 4 Documentation for typography and it says this:

Responsive typography refers to scaling text and components by simply adjusting the root element’s font-size within a series of media queries. Bootstrap doesn’t do this for you, but it’s fairly easy to add if you need it.

Here’s an example of it in practice. Choose whatever font-sizes and media queries you wish.

```<code>html {
  font-size: 1rem;
}

@include media-breakpoint-up(sm) {
  html {
    font-size: 1.2rem;
  }
}

@include media-breakpoint-up(md) {
  html {
    font-size: 1.4rem;
  }
}

@include media-breakpoint-up(lg) {
  html {
    font-size: 1.6rem;
  }
}
</code>```

how do i include that in the _type.scss for the h3 to be responsive the way i want it to be? do i have to use the calc() function of css3? if i have to do that, how do i achieve it?

答:
You can specify it different ways. You could replace the entire h3 line in your _type.scss with the following and modify the values to suit your needs:

```<code>@include media-breakpoint-up(sm) {
  h3, .h3 { $font-size-base * 1.25 !default; }
}

@include media-breakpoint-up(md) {
  h3, .h3 { $font-size-base * 1.5 !default; }
}

@include media-breakpoint-up(lg) {
  h3, .h3 { $font-size-base * 1.75 !default; }
}
</code>```

Personally I don't typically like to modify the default framework partials though, so you can easily go back to defaults.  Doing this can also create upgrade headaches later on.  So what I would do is create another partial called _custom_type.scss, add the above code to it, and compile it into your CSS, just make sure to add your custom overrides after the defaults.

Body:
So, i'm working on a project using Bootstrap 4 sass and i want to make the font-size of the h3 to be responsive.

When i go to the _type.scss, the h3 property looks like this:

h3, .h3 { font-size: $h3-font-size; }

it's calling the variable $h3-font-size from _variables.scss that looks like this:
    $h3-font-size:                $font-size-base * 1.75 !default;

the $font-size-base variable looks like this:

$font-size-base:              1rem !default;

So, this far i know that the font-size of the h3 class is 1.75rem, what i want is that font-size to be 1.5rem from xs to md, and to be 1.75rem from md to lg.

i went to the Bootstrap 4 Documentation for typography and it says this:

Responsive typography refers to scaling text and components by simply adjusting the root element’s font-size within a series of media queries. Bootstrap doesn’t do this for you, but it’s fairly easy to add if you need it.

Here’s an example of it in practice. Choose whatever font-sizes and media queries you wish.

html {
  font-size: 1rem;
}

@include media-breakpoint-up(sm) {
  html {
    font-size: 1.2rem;
  }
}

@include media-breakpoint-up(md) {
  html {
    font-size: 1.4rem;
  }
}

@include media-breakpoint-up(lg) {
  html {
    font-size: 1.6rem;
  }
}

how do i include that in the _type.scss for the h3 to be responsive the way i want it to be? do i have to use the calc() function of css3? if i have to do that, how do i achieve it?

Body:
You can specify it different ways. You could replace the entire h3 line in your _type.scss with the following and modify the values to suit your needs:

@include media-breakpoint-up(sm) {
  h3, .h3 { $font-size-base * 1.25 !default; }
}

@include media-breakpoint-up(md) {
  h3, .h3 { $font-size-base * 1.5 !default; }
}

@include media-breakpoint-up(lg) {
  h3, .h3 { $font-size-base * 1.75 !default; }
}

Personally I don't typically like to modify the default framework partials though, so you can easily go back to defaults.  Doing this can also create upgrade headaches later on.  So what I would do is create another partial called _custom_type.scss, add the above code to it, and compile it into your CSS, just make sure to add your custom overrides after the defaults.


问:
How to detect the "key up" event of the CTRL key when releasing CTRL-F?
I am trying to detect the "key up" event of the CTRL key when releasing CTRL+F in the browser. I have tried this:

```<code>    $(document).keyup(function(e){
        if (e.ctrlKey){ // note that I'm not even checking for the F key here
            console.log("CTRL up");
        }
    });
</code>```

but it doesn't work, the event is not triggered. How can I do this?

答:
If you're using jQuery, you can always do:

```<code>$(document).keydown(function(e) {
  if(e.ctrlKey && (e.keyCode === 70 || e.keyCode === 102)) // f or F
    alert("Ctrl+F was pressed!!");
});
</code>```

from your code:

never use keyup, by that time the browser already fired its own event and the event will never be bubble down to the document again, at least you should use keydown

you will never be able to override the browser behavior, in this case, bring the search input box

Body:
I am trying to detect the "key up" event of the CTRL key when releasing CTRL+F in the browser. I have tried this:

    $(document).keyup(function(e){
        if (e.ctrlKey){ // note that I'm not even checking for the F key here
            console.log("CTRL up");
        }
    });

but it doesn't work, the event is not triggered. How can I do this?

Body:
If you're using jQuery, you can always do:

$(document).keydown(function(e) {
  if(e.ctrlKey && (e.keyCode === 70 || e.keyCode === 102)) // f or F
    alert("Ctrl+F was pressed!!");
});

from your code:

never use keyup, by that time the browser already fired its own event and the event will never be bubble down to the document again, at least you should use keydown

you will never be able to override the browser behavior, in this case, bring the search input box


问:
How to add a WHERE clause to BigQuery Query to find rows where a column value is not in a list of values
I have a table in BigQuery named events that has a column named 'entitlement'.  That column can have values such as 'lapb', 'lacf', 'lasg', 'laxy', 'laza' etc.  It can also have 'null' or '' or other values that I don't know.  It will only have 1 given value per row so it isn't a list of values.  So for example, here is some sample data:

```<code>name    entitlement date
alice   laxy        01072017
bob     null        01082018
charlie lapb        01092017
daniel  lacf        01092017
</code>```

etc

How can I write a query so that I can check if the entitlement value is not in a list of values?

This is how I am currently doing it.  I am adding an additional "and entitlement != clause for each one.

```<code>SELECT *
FROM events
WHERE entitlement != 'lapb' and entitlement != 'lacf'
and entitlement != 'lasg' and entitlement != 'laxy'
and entitlement != 'laza' and entitlement is not null
order by logtime desc
LIMIT 1000
</code>```

I tried doing the following:

```<code>SELECT *
FROM events
WHERE entitlement is not in ['labp', 'lpaf']
order by logtime desc
LIMIT 1000
</code>```

but I get the following error:

Query Failed
Error: Encountered "" at line 3, column 33.

Is there a way in BigQuery to check for only rows that do not contain values in a list or must I add an individual "and entitlement != ..." clause for each additional value?  Basically the query is really becoming large and complicated very quickly and I was trying to find a way to simplify it for manageability and readability purposes.  I tried square brackets, parentheses, nothing, etc but all give me the same error.

答:
Below is for BigQuery Standard SQL   </p>

<pre class="lang-sql prettyprint-override"><code>#standardSQL
WITH events AS (
  SELECT 'alice' AS name, 'laxy' AS entitlement, '01072017' AS DATE UNION ALL
  SELECT 'bob', NULL, '01082018' UNION ALL
  SELECT 'mike', '', '01082018' UNION ALL
  SELECT 'charlie', 'lapb', '01092017' UNION ALL
  SELECT 'dan', 'n/a', '01082018' UNION ALL
  SELECT 'daniel', 'lacf', '01092017'
), known_entitlements AS (
  SELECT entitlement
  FROM UNNEST(['laxy','lapb','lacf']) entitlement
)
SELECT e.*
FROM events e
LEFT JOIN known_entitlements k
ON e.entitlement = k.entitlement
WHERE k.entitlement IS NULL
</code>```

<p>You can add all known entitlements into <code>known_entitlements</code> or you can just have all in separate table   </p>

<p>result is   </p>

<pre class="lang-sql prettyprint-override"><code>name    entitlement date
bob     null        01082018
mike                01082018
dan     n/a         01082018
</code>```

Body:
I have a table in BigQuery named events that has a column named 'entitlement'.  That column can have values such as 'lapb', 'lacf', 'lasg', 'laxy', 'laza' etc.  It can also have 'null' or '' or other values that I don't know.  It will only have 1 given value per row so it isn't a list of values.  So for example, here is some sample data:

name    entitlement date
alice   laxy        01072017
bob     null        01082018
charlie lapb        01092017
daniel  lacf        01092017

etc

How can I write a query so that I can check if the entitlement value is not in a list of values?

This is how I am currently doing it.  I am adding an additional "and entitlement != clause for each one.

SELECT *
FROM events
WHERE entitlement != 'lapb' and entitlement != 'lacf'
and entitlement != 'lasg' and entitlement != 'laxy'
and entitlement != 'laza' and entitlement is not null
order by logtime desc
LIMIT 1000

I tried doing the following:

SELECT *
FROM events
WHERE entitlement is not in ['labp', 'lpaf']
order by logtime desc
LIMIT 1000

but I get the following error:

Query Failed
Error: Encountered "" at line 3, column 33.

Is there a way in BigQuery to check for only rows that do not contain values in a list or must I add an individual "and entitlement != ..." clause for each additional value?  Basically the query is really becoming large and complicated very quickly and I was trying to find a way to simplify it for manageability and readability purposes.  I tried square brackets, parentheses, nothing, etc but all give me the same error.

Body:
Below is for BigQuery Standard SQL

#standardSQL
WITH events AS (
  SELECT 'alice' AS name, 'laxy' AS entitlement, '01072017' AS DATE UNION ALL
  SELECT 'bob', NULL, '01082018' UNION ALL
  SELECT 'mike', '', '01082018' UNION ALL
  SELECT 'charlie', 'lapb', '01092017' UNION ALL
  SELECT 'dan', 'n/a', '01082018' UNION ALL
  SELECT 'daniel', 'lacf', '01092017'
), known_entitlements AS (
  SELECT entitlement
  FROM UNNEST(['laxy','lapb','lacf']) entitlement
)
SELECT e.*
FROM events e
LEFT JOIN known_entitlements k
ON e.entitlement = k.entitlement
WHERE k.entitlement IS NULL

You can add all known entitlements into known_entitlements or you can just have all in separate table

result is

name    entitlement date
bob     null        01082018
mike                01082018
dan     n/a         01082018


问:
How can I average multiple outputs independently in python
PYTHON 3:    Hi, so I have this piece of code

```<code>for money in range(0, 2501, 500):
    print("{} Euro".format(money), end='')
    throws = 0
    d = trump.possession(board)

    while False in d.values():
        prevLoc = piece.location
        piece.move(trump.throw())
        throws += 1
        if piece.location < prevLoc:
            money += 200

        if board.names[piece.location] in d and d[board.names[piece.location]] == False and money >= board.values[piece.location]:
            money -= board.values[piece.location]
            d[board.names[piece.location]] = True
    return throws
</code>```

and this code takes 0 money to start with, runs the code, looks for amount of throws required to buy the entire board, does the same with 500 starting money, 1000 and so forth

my question is, how can i take the average of the throws to buy the entire board for each starting value? the way my code is now it returns the amount of throws for all the starting values, but simulated once, so it may not be accurate.
I searched a lot, and tried some things but i had problems with this one because I want to like run it, say for example, 2000 times, and get the average for each starting value for the money.

anyone got any tips for this? been struggling on it for a while..

i tried making a for loop from 0 to 2000 and then inside of that another for loop that prints 0-2500 and then uses the code below in a function, appends the return value of throws into a list and sums it up and devides it by 2000, it did not turn out so good...

答:
I'm going to assume this is in a function, due to the return statement.  You need to collect outputs into a list and then average that at the end.

```<code>def calc_throws(simulations):
    throw_list = []
    average = lambda x: sum(x)/len(x)
    for i, money in enumerate(range(0, 2501, 500)):
        print("{} Euro".format(money), end='')
        throw_list.append([money, []])
        for _ in range(simulations):
            throws = 0
            d = trump.possession(board)
            while False in d.values():
                prevLoc = piece.location
                piece.move(trump.throw())
                throws += 1
                if piece.location < prevLoc:
                    money += 200

                if board.names[piece.location] in d and d[board.names[piece.location]] == False and money >= board.values[piece.location]:
                    money -= board.values[piece.location]
                    d[board.names[piece.location]] = True
            throw_list[i][1].append(throws)
        throw_list[i][1] = average(throw_list[i][1])
    return throw_list
</code>```

Rather than a single number, this returns a list of lists like #[[0,20],[500,15],...[2500,3]] (or whatever reasonable numbers are) which gives you the average for each amount of starting money.

Body:
PYTHON 3:    Hi, so I have this piece of code

for money in range(0, 2501, 500):
    print("{} Euro".format(money), end='')
    throws = 0
    d = trump.possession(board)

    while False in d.values():
        prevLoc = piece.location
        piece.move(trump.throw())
        throws += 1
        if piece.location < prevLoc:
            money += 200

        if board.names[piece.location] in d and d[board.names[piece.location]] == False and money >= board.values[piece.location]:
            money -= board.values[piece.location]
            d[board.names[piece.location]] = True
    return throws

and this code takes 0 money to start with, runs the code, looks for amount of throws required to buy the entire board, does the same with 500 starting money, 1000 and so forth

my question is, how can i take the average of the throws to buy the entire board for each starting value? the way my code is now it returns the amount of throws for all the starting values, but simulated once, so it may not be accurate.
I searched a lot, and tried some things but i had problems with this one because I want to like run it, say for example, 2000 times, and get the average for each starting value for the money.

anyone got any tips for this? been struggling on it for a while..

i tried making a for loop from 0 to 2000 and then inside of that another for loop that prints 0-2500 and then uses the code below in a function, appends the return value of throws into a list and sums it up and devides it by 2000, it did not turn out so good...

Body:
I'm going to assume this is in a function, due to the return statement.  You need to collect outputs into a list and then average that at the end.

def calc_throws(simulations):
    throw_list = []
    average = lambda x: sum(x)/len(x)
    for i, money in enumerate(range(0, 2501, 500)):
        print("{} Euro".format(money), end='')
        throw_list.append([money, []])
        for _ in range(simulations):
            throws = 0
            d = trump.possession(board)
            while False in d.values():
                prevLoc = piece.location
                piece.move(trump.throw())
                throws += 1
                if piece.location < prevLoc:
                    money += 200

                if board.names[piece.location] in d and d[board.names[piece.location]] == False and money >= board.values[piece.location]:
                    money -= board.values[piece.location]
                    d[board.names[piece.location]] = True
            throw_list[i][1].append(throws)
        throw_list[i][1] = average(throw_list[i][1])
    return throw_list

Rather than a single number, this returns a list of lists like #[[0,20],[500,15],...[2500,3]] (or whatever reasonable numbers are) which gives you the average for each amount of starting money.


问:
sqrt of uint64_t vs. int64_t
I noticed that calculating the integer part of square root of uint64_t is much more complicated than of int64_t. Please, does anybody have an explanation for this? Why is it seemingly much more difficult to deal with one extra bit?

The following:

```<code>int64_t sqrt_int(int64_t a) {
    return sqrt(a);
}
</code>```

compiles with clang 5.0 and -mfpmath=sse -msse3 -Wall -O3 to

```<code>sqrt_int(long):                           # @sqrt_int(long)
        cvtsi2sd        xmm0, rdi
        sqrtsd  xmm0, xmm0
        cvttsd2si       rax, xmm0
        ret
</code>```

But the following:

```<code>uint64_t sqrt_int(uint64_t a) {
    return sqrt(a);
}
</code>```

compiles to:

```<code>.LCPI0_0:
        .long   1127219200              # 0x43300000
        .long   1160773632              # 0x45300000
        .long   0                       # 0x0
        .long   0                       # 0x0
.LCPI0_1:
        .quad   4841369599423283200     # double 4503599627370496
        .quad   4985484787499139072     # double 1.9342813113834067E+25
.LCPI0_2:
        .quad   4890909195324358656     # double 9.2233720368547758E+18
sqrt_int(unsigned long):                           # @sqrt_int(unsigned long)
        movq    xmm0, rdi
        punpckldq       xmm0, xmmword ptr [rip + .LCPI0_0] # xmm0 = xmm0[0],mem[0],xmm0[1],mem[1]
        subpd   xmm0, xmmword ptr [rip + .LCPI0_1]
        haddpd  xmm0, xmm0
        sqrtsd  xmm0, xmm0
        movsd   xmm1, qword ptr [rip + .LCPI0_2] # xmm1 = mem[0],zero
        movapd  xmm2, xmm0
        subsd   xmm2, xmm1
        cvttsd2si       rax, xmm2
        movabs  rcx, -9223372036854775808
        xor     rcx, rax
        cvttsd2si       rax, xmm0
        ucomisd xmm0, xmm1
        cmovae  rax, rcx
        ret
</code>```

答:
First off, you need to be clear that this code is converting 64-bit integers (signed or unsigned) to double precision floating point, taking the square root, and then casting the result back to a signed or unsigned integer.

The answer to your question is because Intel provided 64-bit signed integer to double precision floating-point conversion (and the opposite) in the instruction set you are compiling for, but did not do so for the unsigned case. They added the unsigned conversion instruction in AVX-512, but it does not exist prior to that. So for the signed case, the conversion to double precision and the conversion back are one instruction each. For the unsigned case, the compiler has to synthesize the conversion operation from available instructions.

You can get information on which instructions are available in which versions of SSE2/AVX/AVX-512, etc. here:
    https://software.intel.com/sites/landingpage/IntrinsicsGuide/

You can see discussion of the method used to synthesize the conversion here:
    Are there unsigned equivalents of the x87 FILD and SSE CVTSI2SD instructions?

Title: sqrt of uint64_t vs. int64_t

Body:
I noticed that calculating the integer part of square root of uint64_t is much more complicated than of int64_t. Please, does anybody have an explanation for this? Why is it seemingly much more difficult to deal with one extra bit?

The following:

int64_t sqrt_int(int64_t a) {
    return sqrt(a);
}

compiles with clang 5.0 and -mfpmath=sse -msse3 -Wall -O3 to

sqrt_int(long):                           # @sqrt_int(long)
        cvtsi2sd        xmm0, rdi
        sqrtsd  xmm0, xmm0
        cvttsd2si       rax, xmm0
        ret

But the following:

uint64_t sqrt_int(uint64_t a) {
    return sqrt(a);
}

compiles to:

.LCPI0_0:
        .long   1127219200              # 0x43300000
        .long   1160773632              # 0x45300000
        .long   0                       # 0x0
        .long   0                       # 0x0
.LCPI0_1:
        .quad   4841369599423283200     # double 4503599627370496
        .quad   4985484787499139072     # double 1.9342813113834067E+25
.LCPI0_2:
        .quad   4890909195324358656     # double 9.2233720368547758E+18
sqrt_int(unsigned long):                           # @sqrt_int(unsigned long)
        movq    xmm0, rdi
        punpckldq       xmm0, xmmword ptr [rip + .LCPI0_0] # xmm0 = xmm0[0],mem[0],xmm0[1],mem[1]
        subpd   xmm0, xmmword ptr [rip + .LCPI0_1]
        haddpd  xmm0, xmm0
        sqrtsd  xmm0, xmm0
        movsd   xmm1, qword ptr [rip + .LCPI0_2] # xmm1 = mem[0],zero
        movapd  xmm2, xmm0
        subsd   xmm2, xmm1
        cvttsd2si       rax, xmm2
        movabs  rcx, -9223372036854775808
        xor     rcx, rax
        cvttsd2si       rax, xmm0
        ucomisd xmm0, xmm1
        cmovae  rax, rcx
        ret


问:
Associative array not filling up in server-sent-event environement
I think I'm on the wrong track here:

I have an event source that gives me updates on the underlying system oprations. The page is intended to show said events in a jquery powered treetable. I receieve the events perfectly but I realized that there were a case I did not handle, the case where an event arrives but is missing it's parent. In this case I need to fetch the missing root plus all potentially missing children of that root node from the database. This works fine too.

```<code>//init fct
//...
eventSource.addEventListener("new_node", onEventSourceNewNodeEvent);
//...

function onEventSourceNewNodeEvent(event) {
    let data = event.data;
    if (!data)
        return;

    let rows = $(data).filter("tr");
    rows.each(function (index, row) {
        let parentEventId = row.getAttribute("data-tt-parent-id");
        let parentNode = _table.treetable("node", parentEventId);

        // if headless state is not fully
        // resolved yet keep adding new rows to array
        if (headlessRows[parentEventId]) {
            headlessRows[parentEventId].push(row);
            return;
        } else if (parentEventId && !parentNode) { // headless state found
            if (!headlessRows[parentEventId])
                headlessRows[parentEventId] = [];

            headlessRows[parentEventId].push(row);
            fetchMissingNodes(parentEventId);
            return;
        }

        insertNode(row, parentNode);
    });
}

function fetchMissingNodes(parentEventId) {
    let url = _table.data("url") + parentEventId;

    $.get(url, function (data, textStatus, request) {
        if (!data)
            return;

        let rows = $(data).filter("tr");

        //insert root and children into table
        _table.treetable("loadBranch", null, rows);

        let parentNode = _table.treetable("node", parentEventId);
        let lastLoadedRow = $(rows.last());

        let headlessRowsArray = headlessRows[parentEventId];
        while (headlessRowsArray && headlessRowsArray.length > 0) {
            let row = headlessRowsArray.shift();
            let rowId = row.getAttribute("data-tt-id");
            if (rowId <= lastLoadedRow) // already loaded event from previous fetch
                continue;

            insertNode(row, parentNode);

            let pendingUpdatesArray = pendingUpdates[rowId];
            // shouldn't be more than one but who know future versions
            while (pendingUpdatesArray && pendingUpdatesArray.length > 0) {
                let updateEvent = headlessRowsArray.shift();
                updateNode(updateEvent)
            }
            delete pendingUpdates[rowId]; // <- something better here?
        }
        delete headlessRows[parentEventId]; // <- something better here too?

    });
}
</code>```

The problem is around the line if (headlessRows[parentEventId]).
When I run it step by step (putting a debugger instruction just before) everything works fine, the headless array is created and filled correctly.
But as soon as I let it run full speed everything breaks.
The logs I printed seems to indicate that the array is not behaving in the way I was expecting it to. If I print the array with a console.log it shows as follow :

```<code>(2957754) [empty × 2957754]
    length : 2957754
    __proto__ : Array(0)
</code>```

It seems to be missing any actual data. whereas it shows as follow when I execute it step by step:

```<code>(2957748) [empty × 2957747, Array(1)]
    2957747:[tr.node.UNDETERMINED]
    length:2957748
    __proto__:Array(0)
</code>```

I'm missing something but it is still eluding me.

答:
your code is async, you do http request but you treat him as synchronized code.
try this fix

//init fct
//...
eventSource.addEventListener("new_node", onEventSourceNewNodeEvent);
//...

async function onEventSourceNewNodeEvent(event) {
    let data = event.data;
    if (!data)
        return;

    let rows = $(data).filter("tr");
    rows.each(function (index, row) {
        let parentEventId = row.getAttribute("data-tt-parent-id");
        let parentNode = _table.treetable("node", parentEventId);

        // if headless state is not fully
        // resolved yet keep adding new rows to array
        if (headlessRows[parentEventId]) {
            headlessRows[parentEventId].push(row);
            return;
        } else if (parentEventId && !parentNode) { // headless state found
            if (!headlessRows[parentEventId])
                headlessRows[parentEventId] = [];

            headlessRows[parentEventId].push(row);
            await fetchMissingNodes(parentEventId);
            return;
        }

        insertNode(row, parentNode);
    });
}

function fetchMissingNodes(parentEventId) {
    return new Promise((resolve,reject) =>{
       let url = _table.data("url") + parentEventId;

      $.get(url, function (data, textStatus, request) {
          if (!data){
              resolve()
              return;
          }

          let rows = $(data).filter("tr");

          //insert root and children into table
          _table.treetable("loadBranch", null, rows);

          let parentNode = _table.treetable("node", parentEventId);
          let lastLoadedRow = $(rows.last());

          let headlessRowsArray = headlessRows[parentEventId];
          while (headlessRowsArray && headlessRowsArray.length > 0) {
              let row = headlessRowsArray.shift();
              let rowId = row.getAttribute("data-tt-id");
              if (rowId <= lastLoadedRow) // already loaded event from previous fetch
                  continue;

              insertNode(row, parentNode);

              let pendingUpdatesArray = pendingUpdates[rowId];
              // shouldn't be more than one but who know future versions
              while (pendingUpdatesArray && pendingUpdatesArray.length > 0) {
                  let updateEvent = headlessRowsArray.shift();
                  updateNode(updateEvent)
              }
              delete pendingUpdates[rowId]; // <- something better here?
          }
          delete headlessRows[parentEventId]; // <- something better here too?
           resolve()
      });
    })

}```

Body:
I think I'm on the wrong track here:

I have an event source that gives me updates on the underlying system oprations. The page is intended to show said events in a jquery powered treetable. I receieve the events perfectly but I realized that there were a case I did not handle, the case where an event arrives but is missing it's parent. In this case I need to fetch the missing root plus all potentially missing children of that root node from the database. This works fine too.

//init fct
//...
eventSource.addEventListener("new_node", onEventSourceNewNodeEvent);
//...

function onEventSourceNewNodeEvent(event) {
    let data = event.data;
    if (!data)
        return;

    let rows = $(data).filter("tr");
    rows.each(function (index, row) {
        let parentEventId = row.getAttribute("data-tt-parent-id");
        let parentNode = _table.treetable("node", parentEventId);

        // if headless state is not fully
        // resolved yet keep adding new rows to array
        if (headlessRows[parentEventId]) {
            headlessRows[parentEventId].push(row);
            return;
        } else if (parentEventId && !parentNode) { // headless state found
            if (!headlessRows[parentEventId])
                headlessRows[parentEventId] = [];

            headlessRows[parentEventId].push(row);
            fetchMissingNodes(parentEventId);
            return;
        }

        insertNode(row, parentNode);
    });
}

function fetchMissingNodes(parentEventId) {
    let url = _table.data("url") + parentEventId;

    $.get(url, function (data, textStatus, request) {
        if (!data)
            return;

        let rows = $(data).filter("tr");

        //insert root and children into table
        _table.treetable("loadBranch", null, rows);

        let parentNode = _table.treetable("node", parentEventId);
        let lastLoadedRow = $(rows.last());

        let headlessRowsArray = headlessRows[parentEventId];
        while (headlessRowsArray && headlessRowsArray.length > 0) {
            let row = headlessRowsArray.shift();
            let rowId = row.getAttribute("data-tt-id");
            if (rowId <= lastLoadedRow) // already loaded event from previous fetch
                continue;

            insertNode(row, parentNode);

            let pendingUpdatesArray = pendingUpdates[rowId];
            // shouldn't be more than one but who know future versions
            while (pendingUpdatesArray && pendingUpdatesArray.length > 0) {
                let updateEvent = headlessRowsArray.shift();
                updateNode(updateEvent)
            }
            delete pendingUpdates[rowId]; // <- something better here?
        }
        delete headlessRows[parentEventId]; // <- something better here too?

    });
}

The problem is around the line if (headlessRows[parentEventId]).
When I run it step by step (putting a debugger instruction just before) everything works fine, the headless array is created and filled correctly.
But as soon as I let it run full speed everything breaks.
The logs I printed seems to indicate that the array is not behaving in the way I was expecting it to. If I print the array with a console.log it shows as follow :

(2957754) [empty × 2957754]
    length : 2957754
    __proto__ : Array(0)

It seems to be missing any actual data. whereas it shows as follow when I execute it step by step:

(2957748) [empty × 2957747, Array(1)]
    2957747:[tr.node.UNDETERMINED]
    length:2957748
    __proto__:Array(0)

I'm missing something but it is still eluding me.


答:
You were very close. I always find it easiest to output the e variable in order to see exactly what's going on and filter down from there.
See my jsfiddle for a working example.

```<code>$(document).keyup(function (e) {
  if(e.originalEvent.key == 'Control') {
    console.log("CTRL keyup event.");
  }
});
</code>```

Title: How to detect the "key up" event of the CTRL key when releasing CTRL-F?

Body:
You were very close. I always find it easiest to output the e variable in order to see exactly what's going on and filter down from there.
See my jsfiddle for a working example.

$(document).keyup(function (e) {
  if(e.originalEvent.key == 'Control') {
    console.log("CTRL keyup event.");
  }
});


问:
WUA API unable to find update
Code sample:

```<code>$UpdateSession = New-Object -ComObject 'Microsoft.Update.Session'

$UpdateSearcher = $UpdateSession.CreateUpdateSearcher()
$Updates = $UpdateSearcher.Search('IsInstalled=1')

$Updates | Where-Object { $_.Title -like '*KB2506143*' }
</code>```

I'm trying to uninstall WMF3 programmatically, but I keep getting errors when trying to utilize wusa.exe,

```<code>wusa /uninstall /kb:2506143 /quiet /norestart /log:C:\log.evt
</code>```

CbsClient::CbsClient.00110: Failed to create a CBS session instance

  CbsClient::CbsClient.00127: Exit with error code 0X80040154 (Class not registered)

  UninstallWorker.00664: Start of search

  CbsClient::OpenPackageByKB.00268: CBS session is not initialized.

  CbsClient::OpenPackageByKB.00320: Exit with error code 0X8000ffff (Catastrophic failure)

  UninstallWorker.00667: Failed: OpenPackageByKB() for KB2506143

  UninstallWorker.00799: Exit with error code 0X8000ffff (Catastrophic failure)

  RebootIfRequested.01446: Reboot is not scheduled. IsRunWizardStarted: 0, IsRebootRequired: 0, RestartMode: 1

  Windows update  could not be uninstalled because of error 2147549183 "Catastrophic failure" (Command line: "C:\windows\System32\wusa.exe  /uninstall /kb:2506143 /quiet /norestart /log:C:\log.evt")

  wWinMain.01962: Failed to uninstall update ; Error: 0X8000ffff, Catastrophic failure. Command line: C:\windows\System32\wusa.exe  /uninstall /kb:2506143 /quiet /norestart /log:C:\log.evt

  wWinMain.01998: Exit with error code 0X8000ffff (Catastrophic failure)

so I'm pursuing using the WUA API.  The above code snippet gives me a $Null return, but I can use Get-Hotfix -ID KB2506143 or Get-WmiObject -Class Win32_QuickFixEngineering -Filter 'HotFixID="KB2506143"' to find the update.

This question is similar, but it's getting access denied when trying to uninstall the patch after it has already been found, while my question is: how do I find the patch in the first place?

I'm not sure how the patch got applied, so if I run into the same issue once I find it, I have that resolution at least.

答:
So the purpose of all this was to upgrade to WMF5.1 programmatically and I found a workaround for what I was trying to accomplish.  PowerShell v3 was enabled in the OS using DISM during the build process and cannot be removed by WUA because it wasn't placed there by WUA.

Workaround 1:

```<code>dism.exe /Online /Disable-Feature:MicrosoftWindowsPowerShellV3
</code>```

This downgrades $PSVersionTable to v2, but it does not remove the patch KB2506143.  This causes the need to uninstall it through the UI manually still so it didn't really accomplish what I need.

Workaround 2:

WMF3 cannot be upgraded to WMF5, but it can be upgraded to WMF4, then WMF5(.1).

Ultimately, I installed WMF4 over WMF3 with wusa.exe while still disabling v3 in dism for good measure and was successful installing WMF5.1 over WMF4 after a reboot (again, with wusa.exe).

The limitation is rooted with the WUA not being able to manage patches that it did not install (through a .msu or WSUS)

Title: WUA API unable to find update

Body:
Code sample:

$UpdateSession = New-Object -ComObject 'Microsoft.Update.Session'

$UpdateSearcher = $UpdateSession.CreateUpdateSearcher()
$Updates = $UpdateSearcher.Search('IsInstalled=1')

$Updates | Where-Object { $_.Title -like '*KB2506143*' }

I'm trying to uninstall WMF3 programmatically, but I keep getting errors when trying to utilize wusa.exe,

wusa /uninstall /kb:2506143 /quiet /norestart /log:C:\log.evt

CbsClient::CbsClient.00110: Failed to create a CBS session instance

  CbsClient::CbsClient.00127: Exit with error code 0X80040154 (Class not registered)

  UninstallWorker.00664: Start of search

  CbsClient::OpenPackageByKB.00268: CBS session is not initialized.

  CbsClient::OpenPackageByKB.00320: Exit with error code 0X8000ffff (Catastrophic failure)

  UninstallWorker.00667: Failed: OpenPackageByKB() for KB2506143

  UninstallWorker.00799: Exit with error code 0X8000ffff (Catastrophic failure)

  RebootIfRequested.01446: Reboot is not scheduled. IsRunWizardStarted: 0, IsRebootRequired: 0, RestartMode: 1

  Windows update  could not be uninstalled because of error 2147549183 "Catastrophic failure" (Command line: "C:\windows\System32\wusa.exe  /uninstall /kb:2506143 /quiet /norestart /log:C:\log.evt")

  wWinMain.01962: Failed to uninstall update ; Error: 0X8000ffff, Catastrophic failure. Command line: C:\windows\System32\wusa.exe  /uninstall /kb:2506143 /quiet /norestart /log:C:\log.evt

  wWinMain.01998: Exit with error code 0X8000ffff (Catastrophic failure)

so I'm pursuing using the WUA API.  The above code snippet gives me a $Null return, but I can use Get-Hotfix -ID KB2506143 or Get-WmiObject -Class Win32_QuickFixEngineering -Filter 'HotFixID="KB2506143"' to find the update.

This question is similar, but it's getting access denied when trying to uninstall the patch after it has already been found, while my question is: how do I find the patch in the first place?

I'm not sure how the patch got applied, so if I run into the same issue once I find it, I have that resolution at least.

Body:
So the purpose of all this was to upgrade to WMF5.1 programmatically and I found a workaround for what I was trying to accomplish.  PowerShell v3 was enabled in the OS using DISM during the build process and cannot be removed by WUA because it wasn't placed there by WUA.

Workaround 1:

dism.exe /Online /Disable-Feature:MicrosoftWindowsPowerShellV3

This downgrades $PSVersionTable to v2, but it does not remove the patch KB2506143.  This causes the need to uninstall it through the UI manually still so it didn't really accomplish what I need.

Workaround 2:

WMF3 cannot be upgraded to WMF5, but it can be upgraded to WMF4, then WMF5(.1).

Ultimately, I installed WMF4 over WMF3 with wusa.exe while still disabling v3 in dism for good measure and was successful installing WMF5.1 over WMF4 after a reboot (again, with wusa.exe).

The limitation is rooted with the WUA not being able to manage patches that it did not install (through a .msu or WSUS)


问:
How to use Web Workers with Webextensions?
I'm trying to use a web worker in my webextension to make things run faster, but I can't seem to get even the demo webworker example that MDN provides to work. This is my manifest:

```<code>{
  "manifest_version": 2,
  "name": "test",
  "version": "1.0.0",

  "content_scripts": [
    {
      "matches": [
        "http://*/*",
        "https://*/*"
      ],
      "js": [
        "sharedTest.js"
      ]
    }
  ]
}
</code>```

This is sharedTest.js:

```<code>console.log("js loaded");
if (window.Worker) { // Check if Browser supports the Worker api.
    // Requires script name as input
    var myWorker = new Worker(browser.runtime.getURL('testWorker.js'));
    myWorker.onmessage = function(e) {
        console.log('Message received from worker');
    console.log(e.data);
    };
  myWorker.postMessage([42, 23]); // Sending message as an array to the worker
  console.log('Message posted to worker');
}
</code>```

and this is testWorker.js:

```<code>onmessage = function(e) {
  console.log('Message received from main script');
  var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
  console.log('Posting message back to main script');
  postMessage(workerResult);
}
</code>```

If anyone can tell me what I'm doing wrong or if there is anything missing in my manifest, that'd be great.

答:
So it turns out, due to the same-origin policy, you can't use normal web workers in webextensions. However, you can get around this by wrapping your worker in a blob like so:

```<code>var blob = new Blob([
    `onmessage = function(e) {
       console.log('Message received from main script');
       var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
       console.log('Posting message back to main script');
       postMessage(workerResult);
     }`]);

// Obtain a blob URL reference to our worker 'file'.
var blobURL = window.URL.createObjectURL(blob);

var worker = new Worker(blobURL);
worker.onmessage = function(e) {
    console.log('Message received from worker');
    console.log(e.data);
};
  worker.postMessage([42, 23]); // Sending message as an array to the worker
  console.log('Message posted to worker');
</code>```

And that will work. The above example was based on this article, and that does work in webextensions (for theoretically everything but Internet Explorer). However, that blob worker is not within the same origin as the rest of your extension anymore, so due to the same-origin policy, the global importScripts() will not work to import any files in your extension. This means that you have to include all necessary methods and logic within the Blob, which is less than ideal.

Alternatively, I realized that this is kind of what background scripts are for, or for my case, event pages.

Body:
I'm trying to use a web worker in my webextension to make things run faster, but I can't seem to get even the demo webworker example that MDN provides to work. This is my manifest:

{
  "manifest_version": 2,
  "name": "test",
  "version": "1.0.0",

  "content_scripts": [
    {
      "matches": [
        "http://*/*",
        "https://*/*"
      ],
      "js": [
        "sharedTest.js"
      ]
    }
  ]
}

This is sharedTest.js:

console.log("js loaded");
if (window.Worker) { // Check if Browser supports the Worker api.
    // Requires script name as input
    var myWorker = new Worker(browser.runtime.getURL('testWorker.js'));
    myWorker.onmessage = function(e) {
        console.log('Message received from worker');
    console.log(e.data);
    };
  myWorker.postMessage([42, 23]); // Sending message as an array to the worker
  console.log('Message posted to worker');
}

and this is testWorker.js:

onmessage = function(e) {
  console.log('Message received from main script');
  var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
  console.log('Posting message back to main script');
  postMessage(workerResult);
}

If anyone can tell me what I'm doing wrong or if there is anything missing in my manifest, that'd be great.

Body:
So it turns out, due to the same-origin policy, you can't use normal web workers in webextensions. However, you can get around this by wrapping your worker in a blob like so:

var blob = new Blob([
    `onmessage = function(e) {
       console.log('Message received from main script');
       var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
       console.log('Posting message back to main script');
       postMessage(workerResult);
     }`]);

// Obtain a blob URL reference to our worker 'file'.
var blobURL = window.URL.createObjectURL(blob);

var worker = new Worker(blobURL);
worker.onmessage = function(e) {
    console.log('Message received from worker');
    console.log(e.data);
};
  worker.postMessage([42, 23]); // Sending message as an array to the worker
  console.log('Message posted to worker');

And that will work. The above example was based on this article, and that does work in webextensions (for theoretically everything but Internet Explorer). However, that blob worker is not within the same origin as the rest of your extension anymore, so due to the same-origin policy, the global importScripts() will not work to import any files in your extension. This means that you have to include all necessary methods and logic within the Blob, which is less than ideal.

Alternatively, I realized that this is kind of what background scripts are for, or for my case, event pages.


问:
No fields beyond id found when importing into Azure Search from CosmosDB
I am attempting to import data into azure search from cosmosdb and the import wizard does not detect any fields beyond id.  If I import from Azure Table or the Sample data set then the import works as expected.  Is there something I am overlooking, such as a required set of fields on my document in cosmos?

Import Query

```<code>SELECT c.id, c.first, c.last, c.address, c.city, c.state, c.zip, c.dob, c.sex, c._ts from c where c._ts > @HighWaterMark order by c._ts
</code>```

Cosmos Document

```<code>{
    "_id" : "1d202fb9-f384-42f4-a5f8-bf729b776576",
    "first" : "Mata",
    "middle" : "Hari",
    "last" : "Drentlaw",
    "address" : "3226 16TH ST",
    "city" : "QUEENS",
    "state" : "PA",
    "zip" : "10465",
    "sex" : "O",
    "dob" : "1984/03/01",
    "dod" : null,
    "language" : "HiriMotu",
    "ssn" : "123456789",
    "ethnicity" : "Asturian",
    "ethnicityCode" : "2139-4",
    "phone" : "1-555-867-5309",
    "maritalStatus" : "Married",
    "martialStatusCode" : "M",
    "race" : "Georgetown"
}
</code>```

答: Turned out this was a Mongo DB collection. Currently, Azure Search indexer only supports "classic" Cosmos DB collections. We're working on adding support for Mongo DB. To help us prioritize that work and get status updates, please vote for DocumentDB indexer should be able to index MongoDb collections UserVoice suggestion.   </p>

Body:
I am attempting to import data into azure search from cosmosdb and the import wizard does not detect any fields beyond id.  If I import from Azure Table or the Sample data set then the import works as expected.  Is there something I am overlooking, such as a required set of fields on my document in cosmos?

Import Query

SELECT c.id, c.first, c.last, c.address, c.city, c.state, c.zip, c.dob, c.sex, c._ts from c where c._ts > @HighWaterMark order by c._ts

Cosmos Document

{
    "_id" : "1d202fb9-f384-42f4-a5f8-bf729b776576",
    "first" : "Mata",
    "middle" : "Hari",
    "last" : "Drentlaw",
    "address" : "3226 16TH ST",
    "city" : "QUEENS",
    "state" : "PA",
    "zip" : "10465",
    "sex" : "O",
    "dob" : "1984/03/01",
    "dod" : null,
    "language" : "HiriMotu",
    "ssn" : "123456789",
    "ethnicity" : "Asturian",
    "ethnicityCode" : "2139-4",
    "phone" : "1-555-867-5309",
    "maritalStatus" : "Married",
    "martialStatusCode" : "M",
    "race" : "Georgetown"
}


问:
Multithreading in c++
I want to run one function with different parameters on different threads:

```<code>int threads = 3;
int par1[] = {1, 2, 3};
int par2[] = {4, 5, 6};
for (int i=0; i<threads; i++){
  //new_thread function(par1[i], par2[i]);
}
</code>```

I know nothing about threads. I tried to do something the windows API (can't use other libraries), but it doesn't work. How should I implement this? And it is possible to start an unknown number of threads of the time of programming (dynamically creating threads)?

答:
You need to do a couple of things to get this to work. First of all the windows thread function takes this signature:

```<code>DWORD WINAPI ThreadFunction(LPVOID args)
</code>```

The thread startup routine is this function:

```<code>HANDLE WINAPI CreateThread(
  __in_opt   LPSECURITY_ATTRIBUTES lpThreadAttributes,
  __in       SIZE_T dwStackSize,
  __in       LPTHREAD_START_ROUTINE lpStartAddress,
  __in_opt   LPVOID lpParameter,
  __in       DWORD dwCreationFlags,
  __out_opt  LPDWORD lpThreadId
);
</code>```

Note that the way to pass arguments to your thread function is through an LPVOID. That means you need to create a structure to hold your par1 and par2. You would then pass in a pointer to this structure and the pull the contents out in your thread routine.

Title: Multithreading in c++

Body:
I want to run one function with different parameters on different threads:

int threads = 3;
int par1[] = {1, 2, 3};
int par2[] = {4, 5, 6};
for (int i=0; i<threads; i++){
  //new_thread function(par1[i], par2[i]);
}

I know nothing about threads. I tried to do something the windows API (can't use other libraries), but it doesn't work. How should I implement this? And it is possible to start an unknown number of threads of the time of programming (dynamically creating threads)?

Body:
You need to do a couple of things to get this to work. First of all the windows thread function takes this signature:

DWORD WINAPI ThreadFunction(LPVOID args)

The thread startup routine is this function:

HANDLE WINAPI CreateThread(
  __in_opt   LPSECURITY_ATTRIBUTES lpThreadAttributes,
  __in       SIZE_T dwStackSize,
  __in       LPTHREAD_START_ROUTINE lpStartAddress,
  __in_opt   LPVOID lpParameter,
  __in       DWORD dwCreationFlags,
  __out_opt  LPDWORD lpThreadId
);

Note that the way to pass arguments to your thread function is through an LPVOID. That means you need to create a structure to hold your par1 and par2. You would then pass in a pointer to this structure and the pull the contents out in your thread routine.


问:
Regular expression for Medicare MBI number format
I'm wondering if someone can help me to create a regular expression to check if a string matches the new Medicare MBI number format.  Here are the specifics in regards to character position and what they can contain.

I'm using Cache ObjectScript, but any language would be helpful just so I can get the idea.

答:
If PCRE is an option, you could leverage subroutines:

```<code>(?(DEFINE)
    (?P<numeric>\d)                    # numbers
    (?P<abc>(?![SLOIBZ])[A-Z])         # A-Z without S,L,O,I,B,Z
    (?P<both>(?&numeric)|(?&abc))      # combined
)
^                                      # start of line/string
(?&numeric)(?&abc)(?&both)             # in packs of three
(?&numeric)(?&abc)(?&both)
(?&numeric)(?&abc)(?&abc)
(?&numeric)(?&numeric)
$                                      # end of line/string
</code>```

Paste your IDs into the demo on regex101.com (but don't save it on regex101 or you'll expose those IDs to the public permanently).

Of course, it is not a must to use subroutines, it just makes the expression clearer, more readable and maintainable.

But, you could very well go for

```<code>^
\d
(?![SLOIBZ])[A-Z]
\d|(?![SLOIBZ])[A-Z]
\d
(?![SLOIBZ])[A-Z]
\d|(?![SLOIBZ])[A-Z]
\d
(?![SLOIBZ])[A-Z]
(?![SLOIBZ])[A-Z]
\d
\d
$
</code>```

Or condensed (just copy and paste it):

```<code>^\d(?![SLOIBZ])[A-Z]\d|(?![SLOIBZ])[A-Z]\d(?![SLOIBZ])[A-Z]\d|(?![SLOIBZ])[A-Z]\d(?![SLOIBZ])[A-Z](?![SLOIBZ])[A-Z]\d\d$
</code>```

Body:
If PCRE is an option, you could leverage subroutines:

(?(DEFINE)
    (?P<numeric>\d)                    # numbers
    (?P<abc>(?![SLOIBZ])[A-Z])         # A-Z without S,L,O,I,B,Z
    (?P<both>(?&numeric)|(?&abc))      # combined
)
^                                      # start of line/string
(?&numeric)(?&abc)(?&both)             # in packs of three
(?&numeric)(?&abc)(?&both)
(?&numeric)(?&abc)(?&abc)
(?&numeric)(?&numeric)
$                                      # end of line/string

Paste your IDs into the demo on regex101.com (but don't save it on regex101 or you'll expose those IDs to the public permanently).

Of course, it is not a must to use subroutines, it just makes the expression clearer, more readable and maintainable.

But, you could very well go for

^
\d
(?![SLOIBZ])[A-Z]
\d|(?![SLOIBZ])[A-Z]
\d
(?![SLOIBZ])[A-Z]
\d|(?![SLOIBZ])[A-Z]
\d
(?![SLOIBZ])[A-Z]
(?![SLOIBZ])[A-Z]
\d
\d
$

Or condensed (just copy and paste it):

^\d(?![SLOIBZ])[A-Z]\d|(?![SLOIBZ])[A-Z]\d(?![SLOIBZ])[A-Z]\d|(?![SLOIBZ])[A-Z]\d(?![SLOIBZ])[A-Z](?![SLOIBZ])[A-Z]\d\d$


问:
Why is perl complaining about a "my" when the line does not have one?
I have code that tries to call a function multiple times, given a list. I have a for() loop, and then inside the loop I call the function. However on the line with the function call, I get a strange error:

```<code>[Thu Aug  8 08:31:37 2013] x.cgi: "my" variable $_ masks earlier declaration in same statement at /usr/home/x/public_html/cgi-bin/x.cgi line 310.
[Thu Aug  8 08:31:37 2013] x.cgi: "my" variable $_ masks earlier declaration in same statement at /usr/home/x/public_html/cgi-bin/x.cgi line 310.
</code>```

The error is strange because the line does not have a my in it at all.

Here's my code, run with perl 5.

sub cgiPrintForm {
    my $fh = shift;
    for (qw!betatest subscribe fname lname position department company address1 address2 city province postalcode country phone fax email hearofus comments!)
    {
      print $fh "\n$_: ",param($_) if defined(param($_));
    }
    print $fh
      "\nReferer: ",referer(),
      "\nRemote Host: ",remote_host(),
      "\nRemote IP: ",remote_addr(),
      "\nRemote Ident: ",remote_ident(),
      "\nUser Agent: ",user_agent(),"\n";
}
```

Obviously some of Perl's magic has gone wrong and the automatic my is messing me up.

答:
This error message often indicates that you forgot a semicolon far before the line where the error occurred. I would look immediately before this sub definition for possible errors. – amon Aug 8 '13 at 14:23

@amon's comment was correct; I had an error in another section that wasn't detected until this point (it was a missing quote or braces or something).

Body:
I have code that tries to call a function multiple times, given a list. I have a for() loop, and then inside the loop I call the function. However on the line with the function call, I get a strange error:

[Thu Aug  8 08:31:37 2013] x.cgi: "my" variable $_ masks earlier declaration in same statement at /usr/home/x/public_html/cgi-bin/x.cgi line 310.
[Thu Aug  8 08:31:37 2013] x.cgi: "my" variable $_ masks earlier declaration in same statement at /usr/home/x/public_html/cgi-bin/x.cgi line 310.

The error is strange because the line does not have a my in it at all.

Here's my code, run with perl 5.

sub cgiPrintForm {
    my $fh = shift;
    for (qw!betatest subscribe fname lname position department company address1 address2 city province postalcode country phone fax email hearofus comments!)
    {
      print $fh "\n$_: ",param($_) if defined(param($_));
    }
    print $fh
      "\nReferer: ",referer(),
      "\nRemote Host: ",remote_host(),
      "\nRemote IP: ",remote_addr(),
      "\nRemote Ident: ",remote_ident(),
      "\nUser Agent: ",user_agent(),"\n";
}

Obviously some of Perl's magic has gone wrong and the automatic my is messing me up.