问:
Two windows appear instead of one using Rust
I tried loading the minimal.html, it is loading fine at cargo run, but once I runn the .exe alone, 2 windows appear, one empty console windows and one shows the real output as shown in this pic.

I'm using Windows 10 x64

My main.rs is:

```<code>extern crate sciter;

fn main() {
    let html = include_bytes!("minimal.htm");
    let mut frame = sciter::Window::new();
    frame.load_html(html, None);
    frame.run_app();
}
</code>```

The Cargo.toml is:

```<code>[package]
name = "rust_sciter"
version = "0.1.0"
authors = ["Home"]

[dependencies]
sciter-rs = "0.4.24"
</code>```

The minimal.html is:

```<code><html window-icon="https://sciter.com/wp-content/themes/sciter/!images/favicon.ico">
<head>
  <title>Minimalistic Sciter demo</title>
  <style>
    html {
      background: radial-gradient(75% 75%, circle farthest-side, white, orange, rgb(0,0,204));
      color:#fff;
    }
    html:rtl {
      mapping: left-to-right(background);
    }
  </style>
  <script type="text/tiscript">
    view.caption = $(head > title).value;
    $(#machine).text = Sciter.machineName();
    var counter = 0;
    $(button#append).on("click", function(){
      $(body).$append(<h1#test>{++counter }</h1>);
    });
    $(button#open).on("click", function(){
      var fn = view.selectFile(#open,
        "HTML Files (*.htm,*.html)|*.HTM;*.HTML|All Files (*.*)|*.*" , "html" );
      stdout.println("selected file: " + fn);
      $(body).$append(<h1#test>{fn}</h1>);
    });
  </script>
</head>
<body>

<h1>Minimal Sciter Application</h1>
<p>Running on <em #machine /> machine</p>

<button #append>Append</button>
<button #open>Open</button>
<select>
  <option>First</option>
  <option>Second</option>
  <option>Third</option>
</select>

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

The app structure, code and output are below:

答:
I found the answer here, #![windows_subsystem="windows"] is required to be used in the top of the code, so my code became:

```<code>#![windows_subsystem = "windows"]
extern crate sciter;

fn main() {
    let html = include_bytes!("minimal.htm");
    let mut frame = sciter::Window::new();
    frame.load_html(html, None);
    frame.run_app();
}
</code>```

Body:
I tried loading the minimal.html, it is loading fine at cargo run, but once I runn the .exe alone, 2 windows appear, one empty console windows and one shows the real output as shown in this pic.

I'm using Windows 10 x64

My main.rs is:

extern crate sciter;

fn main() {
    let html = include_bytes!("minimal.htm");
    let mut frame = sciter::Window::new();
    frame.load_html(html, None);
    frame.run_app();
}

The Cargo.toml is:

[package]
name = "rust_sciter"
version = "0.1.0"
authors = ["Home"]

[dependencies]
sciter-rs = "0.4.24"

The minimal.html is:

  <title>Minimalistic Sciter demo</title>

Minimal Sciter Application

Running on  machine

<button #append>Append</button>
<button #open>Open</button>
<select>
  <option>First</option>
  <option>Second</option>
  <option>Third</option>
</select>

The app structure, code and output are below:

Body:
I found the answer here, #![windows_subsystem="windows"] is required to be used in the top of the code, so my code became:

#![windows_subsystem = "windows"]
extern crate sciter;

fn main() {
    let html = include_bytes!("minimal.htm");
    let mut frame = sciter::Window::new();
    frame.load_html(html, None);
    frame.run_app();
}


来源: stackexchange

问:
"Unexpected end of input - expecting end of input" in parsec
Consider this parsec parser (put in a file parsec-eof-test.hs):

```<code>import Text.Parsec
import Text.Parsec.String

main = do
  x <- parse (manyTill anyChar eof >> fail "forced fail") "" <$> readFile "parsec-eof-test.hs"
  print (x :: Either ParseError String)
</code>```

If you run it, you get:

```<code>Left (line 7, column 1):
unexpected end of input
expecting end of input
forced fail
</code>```

unexpected end of input - expecting end of input - that doesn't make any sense, it's a contradiction.

What's going on here?

Is it a bad default in parsec, or is what I'm looking at actually some stack of potential errors that parsec came by while parsing?

Since my parser manyTill anyChar eof consumes input, I'd expect the only error message to be emitted to be forced fail. What am I missing?

答:
Works with Megaparsec as expected:

```<code>module Main (main) where

import Data.Void
import Text.Megaparsec
import Text.Megaparsec.Char

type Parser = Parsec Void String

main :: IO ()
main = do
  parseTest' (manyTill anyChar eof >> fail "forced fail" :: Parser String)
    "somethingsomething"
</code>```

When I run it, I get:

```<code>1:19:
  |
1 | somethingsomething
  |                   ^
forced fail
</code>```

The reason you get that error message with Parsec is that (if I remember correctly) Parsec internally uses a lot of questionable "conventions". One such convention is that "unexpected end of input" is represented by the absence of other unexpected items. This just asks for trouble, sure. When I started turning Parsec into Megaparsec, I was scared that this is the Haskell's "industrial strength" parsing library.

Why you get no other unexpected components? Because fail, which actually causes your parser to fail (as you expect) does not generate any of them. Nor does it generate expected components, but those (in your case it's the "expecting end of input" part) are picked up and merged into your fail error message because of this feature:

```<code>λ> parseTest (many (char 'a') *> many (char 'b') *> empty) ""
parse error at (line 1, column 1):
unexpected end of input
expecting "a" or "b"
</code>```

Parsec is clever enough to figure out that "a" and "b" are still possible here. Makes sense in this case, but lets you down with fail.

Error messages in Parsec are a crazy thing, it's absolutely insane if you start to read the code critically.

P.S. I don't mean to be mean, but let's call a shovel a shovel.

ContentLicense: CC BY-SA 3.0

Body:
Consider this parsec parser (put in a file parsec-eof-test.hs):

import Text.Parsec
import Text.Parsec.String

main = do
  x <- parse (manyTill anyChar eof >> fail "forced fail") "" <$> readFile "parsec-eof-test.hs"
  print (x :: Either ParseError String)

If you run it, you get:

Left (line 7, column 1):
unexpected end of input
expecting end of input
forced fail

unexpected end of input - expecting end of input - that doesn't make any sense, it's a contradiction.

What's going on here?

Is it a bad default in parsec, or is what I'm looking at actually some stack of potential errors that parsec came by while parsing?

Since my parser manyTill anyChar eof consumes input, I'd expect the only error message to be emitted to be forced fail. What am I missing?

Body:
Works with Megaparsec as expected:

module Main (main) where

import Data.Void
import Text.Megaparsec
import Text.Megaparsec.Char

type Parser = Parsec Void String

main :: IO ()
main = do
  parseTest' (manyTill anyChar eof >> fail "forced fail" :: Parser String)
    "somethingsomething"

When I run it, I get:

1:19:
  |
1 | somethingsomething
  |                   ^
forced fail

The reason you get that error message with Parsec is that (if I remember correctly) Parsec internally uses a lot of questionable "conventions". One such convention is that "unexpected end of input" is represented by the absence of other unexpected items. This just asks for trouble, sure. When I started turning Parsec into Megaparsec, I was scared that this is the Haskell's "industrial strength" parsing library.

Why you get no other unexpected components? Because fail, which actually causes your parser to fail (as you expect) does not generate any of them. Nor does it generate expected components, but those (in your case it's the "expecting end of input" part) are picked up and merged into your fail error message because of this feature:

λ> parseTest (many (char 'a') *> many (char 'b') *> empty) ""
parse error at (line 1, column 1):
unexpected end of input
expecting "a" or "b"

Parsec is clever enough to figure out that "a" and "b" are still possible here. Makes sense in this case, but lets you down with fail.

Error messages in Parsec are a crazy thing, it's absolutely insane if you start to read the code critically.

P.S. I don't mean to be mean, but let's call a shovel a shovel.


问:
how to create tooltips with javascript for tabs
Hi I would like to use javascript to control what tooltip displays when a tab is rolled over depending on which tab was clicked.

```<code> <li id='1tab_1a' class='selected'>a id='1link_1a'  title="Customer Info Screen"><span >Customer Info</span></a></li>
  <li id='1tab_1b' >a id='1link_1b'  title="Order Detail"  ><span>Order</span></a></li>

 <li id='1tab_1c' >a id='1link_1c'  title="Phone Detail" ><span>Phone:  7093521232</span></a></li>
</code>```

For example when the Customer Info tab is selected I would like the tooltips to be like above but when Order is the tab selected I would like the
tooltip to say Customer Info Detail, Order Detail Screen, and Phone Detail. How could I use an onclick event to control what tooltip is being
displayed depending on which tab is selected? I have about 20 sets of customer info and sometimes not everyone contains all of the tabs and I
would also like to be able to add more customers.

答:
I've partially tested this code, and I think it may work for you. This assumes that the
 are inside a
, and you have added onclick="onClick(this)" to the  tags.

```<code>function onClick(obj) {
    var a, li, selected, ul = obj.parentNode.parentNode;

    for (var i=0; i<ul.childNodes.length; i++) {
    li = ul.childNodes[i];

        if (li.nodeName.toUpperCase()=="LI") {
            selected = (li.className=="selected");
            a = li.firstChild;

            switch (li.id) {
                case "1tab_1a": a.title = (selected)?"Customer Info Screen":"Customer Info Detail"; break;
                case "1tab_1b": a.title = (selected)?"Order Screen":"Order Detail"; break;
                case "1tab_1c": a.title = (selected)?"Phone Screen":"Phone Detail"; break;
            }
        }
    }
}
</code>```

EDIT: It looks like your sample HTML code is missing some open tag symbols before the  tags.

EDIT: This method is based on the class attribute of the
 tags. I'm not sure how you are currently changing that value to "selected". You could wrap it into this onclick function by adding the following to the first line under the if:

```<code>li.className = (li==obj.parentNode)?"selected":"";
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Hi I would like to use javascript to control what tooltip displays when a tab is rolled over depending on which tab was clicked.

a id='1link_1a'  title="Customer Info Screen">Customer Info

a id='1link_1b'  title="Order Detail"  >Order

a id='1link_1c'  title="Phone Detail" >Phone:  7093521232

For example when the Customer Info tab is selected I would like the tooltips to be like above but when Order is the tab selected I would like the
tooltip to say Customer Info Detail, Order Detail Screen, and Phone Detail. How could I use an onclick event to control what tooltip is being
displayed depending on which tab is selected? I have about 20 sets of customer info and sometimes not everyone contains all of the tabs and I
would also like to be able to add more customers.

Body:
I've partially tested this code, and I think it may work for you. This assumes that the <li> are inside a <ul>, and you have added onclick="onClick(this)" to the <a> tags.

function onClick(obj) {
    var a, li, selected, ul = obj.parentNode.parentNode;

    for (var i=0; i<ul.childNodes.length; i++) {
    li = ul.childNodes[i];

        if (li.nodeName.toUpperCase()=="LI") {
            selected = (li.className=="selected");
            a = li.firstChild;

            switch (li.id) {
                case "1tab_1a": a.title = (selected)?"Customer Info Screen":"Customer Info Detail"; break;
                case "1tab_1b": a.title = (selected)?"Order Screen":"Order Detail"; break;
                case "1tab_1c": a.title = (selected)?"Phone Screen":"Phone Detail"; break;
            }
        }
    }
}

EDIT: It looks like your sample HTML code is missing some open tag symbols before the <a> tags.

EDIT: This method is based on the class attribute of the <li> tags. I'm not sure how you are currently changing that value to "selected". You could wrap it into this onclick function by adding the following to the first line under the if:

li.className = (li==obj.parentNode)?"selected":"";


问:
Not able to install python-pip on SUSE
I have a sandbox environment of SUSE Linux Enterprise Server 11 SP3 for VMware  (x86_64), and trying to install python-pip on it through terminal using this command:

```<code>sudo zypper in python-pip
</code>```

I am getting this message: Package 'python-pip' not found.

I tried to install pip using python get-pip.py after downloading get-pip.py
It gives me this:

```<code>Could not find any downloads that satisfy the requirement pip
No distributions at all found for pip
</code>```

答:
Example for SLES12 SP3:</p>

```<code>touch  /etc/zypp/repos.d/devel_languages_python.repo
cat < EOF > /etc/zypp/repos.d/devel_languages_python.repo
[devel_languages_python]
name=Python Modules (SLE_12_SP3)
type=rpm-md
baseurl=http://download.opensuse.org/repositories/devel:/languages:/python/SLE_12_SP3/
gpgcheck=1
gpgkey=http://download.opensuse.org/repositories/devel:/languages:/python/SLE_12_SP3/repodata/repomd.xml.key
enabled=1
EOF
zypper ref
# choose trust when asked for the signing key
zypper in -y python-pip
</code>```

ContentLicense: CC BY-SA 4.0

Title: Not able to install python-pip on SUSE

Body:
I have a sandbox environment of SUSE Linux Enterprise Server 11 SP3 for VMware  (x86_64), and trying to install python-pip on it through terminal using this command:

sudo zypper in python-pip

I am getting this message: Package 'python-pip' not found.

I tried to install pip using python get-pip.py after downloading get-pip.py
It gives me this:

Could not find any downloads that satisfy the requirement pip
No distributions at all found for pip

Body:
Example for SLES12 SP3:

touch  /etc/zypp/repos.d/devel_languages_python.repo
cat < EOF > /etc/zypp/repos.d/devel_languages_python.repo
[devel_languages_python]
name=Python Modules (SLE_12_SP3)
type=rpm-md
baseurl=http://download.opensuse.org/repositories/devel:/languages:/python/SLE_12_SP3/
gpgcheck=1
gpgkey=http://download.opensuse.org/repositories/devel:/languages:/python/SLE_12_SP3/repodata/repomd.xml.key
enabled=1
EOF
zypper ref
# choose trust when asked for the signing key
zypper in -y python-pip


问:
Electron webview spellchecker not working
We are building an app which uses Electron and at one point we are popping out a window which is a third-party website. If I open the website using chrome or any other browser then the spell checking works as normal. Opening the page in a webview inside Electron it doesn't.

Does Electron/Chromium not support spell-checking or is there something which needs to be enabled?

Note: We have no control over the contents or code of the third-party website

答:
After some investigation, I found that Electron does not have a default spellchecker but there are plenty of modules which can help.

Electron Spellchecker is the one we went for as it has good support.


问:
PIP cannot install Django inside VIrtualenv
```<code>(myenv) wanjila@wanjila:~/Desktop/Python-Area/projects/Djangular$ pip freeze
djangorestframework==3.7.3
pkg-resources==0.0.0
(myenv) wanjila@wanjila:~/Desktop/Python-Area/projects/Djangular$ pip install django
Collecting django
  Using cached Django-2.0.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-qAnv7G/django/setup.py", line 32, in <module>
        version = __import__('django').get_version()
      File "django/__init__.py", line 1, in <module>
        from django.utils.version import get_version
      File "django/utils/version.py", line 61, in <module>
        @functools.lru_cache()
    AttributeError: 'module' object has no attribute 'lru_cache'

------------------------------------
</code>```

I keep getting that error whenever i try to pip install django while inside my virtualenv. How can i fix this.

答:
Make sure your Python version in the virtualenv is Python 3.4+.

Django 2.0 only supports Python 3.4+, and functools.lru_cache is only available in 3.2+.

To check the Python version in your current virtualenv:

```<code>python --version
</code>```

To create a new virtualenv with python 3:

```<code>python3 -m venv venv --prompt=myenv
</code>```

Body:
(myenv) wanjila@wanjila:~/Desktop/Python-Area/projects/Djangular$ pip freeze
djangorestframework==3.7.3
pkg-resources==0.0.0
(myenv) wanjila@wanjila:~/Desktop/Python-Area/projects/Djangular$ pip install django
Collecting django
  Using cached Django-2.0.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-qAnv7G/django/setup.py", line 32, in <module>
        version = __import__('django').get_version()
      File "django/__init__.py", line 1, in <module>
        from django.utils.version import get_version
      File "django/utils/version.py", line 61, in <module>
        @functools.lru_cache()
    AttributeError: 'module' object has no attribute 'lru_cache'

------------------------------------

I keep getting that error whenever i try to pip install django while inside my virtualenv. How can i fix this.

Body:
Make sure your Python version in the virtualenv is Python 3.4+.

Django 2.0 only supports Python 3.4+, and functools.lru_cache is only available in 3.2+.

To check the Python version in your current virtualenv:

python --version

To create a new virtualenv with python 3:

python3 -m venv venv --prompt=myenv


问:
R - Remove all outliers at once
I have a data set imported in R where I am trying to remove the outliers. I did it so far that I identified all outlier values with a boxplot and saved them in a variable.

```<code>outlier_values_2 <- boxplot.stats(myfileswoNA$smart_1_raw)$out  # outlier values.
boxplot(myfileswoNA$smart_1_raw, main="Outlier", boxwex=0.1)

hist(myfileswoNA$smart_1_raw)
summary(myfileswoNA$smart_1_raw)
</code>```

Now I am trying to remove the lines with the identified outliers. I can do this with one certain value:

```<code>example <- myfileswoNA[myfileswoNA$smart_1_raw!=4294967295,]
</code>```

But what I would like to do is to remove all outliers at once, which are stored in the variable outlier_values_2
For example this way is not working:

```<code>example <- myfileswoNA[myfileswoNA$smart_1_raw!=4294967295,]
</code>```

Can anyone help me with this issue? Or does anyone have an idea?

答:
The answer from @LAP helped me with my problem.
Here is what he suggested:

If all outlier values are stored in outlier_values_2,
  try
  myfileswoNA[!myfileswoNA$smart_1_raw %in% outlier_values_2,]

Title: R - Remove all outliers at once

Body:
I have a data set imported in R where I am trying to remove the outliers. I did it so far that I identified all outlier values with a boxplot and saved them in a variable.

outlier_values_2 <- boxplot.stats(myfileswoNA$smart_1_raw)$out  # outlier values.
boxplot(myfileswoNA$smart_1_raw, main="Outlier", boxwex=0.1)

hist(myfileswoNA$smart_1_raw)
summary(myfileswoNA$smart_1_raw)

Now I am trying to remove the lines with the identified outliers. I can do this with one certain value:

example <- myfileswoNA[myfileswoNA$smart_1_raw!=4294967295,]

But what I would like to do is to remove all outliers at once, which are stored in the variable outlier_values_2
For example this way is not working:

example <- myfileswoNA[myfileswoNA$smart_1_raw!=4294967295,]

Can anyone help me with this issue? Or does anyone have an idea?


问:
How to avoid the "Circular view path" exception with Spring MVC test
I have the following code in one of my controllers:

```<code>@Controller
@RequestMapping("/preference")
public class PreferenceController {

    @RequestMapping(method = RequestMethod.GET, produces = "text/html")
    public String preference() {
        return "preference";
    }
}
</code>```

I am simply trying to test it using Spring MVC test as follows:

```<code>@ContextConfiguration
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class PreferenceControllerTest {

    @Autowired
    private WebApplicationContext ctx;

    private MockMvc mockMvc;
    @Before
    public void setup() {
        mockMvc = webAppContextSetup(ctx).build();
    }

    @Test
    public void circularViewPathIssue() throws Exception {
        mockMvc.perform(get("/preference"))
               .andDo(print());
    }
}
</code>```

I am getting the following exception:

Circular view path [preference]: would dispatch back to the current
  handler URL [/preference] again. Check your ViewResolver setup! (Hint:
  This may be the result of an unspecified view, due to default view
  name generation.)

What I find strange is that it works fine when I load the "full" context configuration that includes the template and view resolvers as shown below:

```<code><bean class="org.thymeleaf.templateresolver.ServletContextTemplateResolver" id="webTemplateResolver">
    <property name="prefix" value="WEB-INF/web-templates/" />
    <property name="suffix" value=".html" />
    <property name="templateMode" value="HTML5" />
    <property name="characterEncoding" value="UTF-8" />
    <property name="order" value="2" />
    <property name="cacheable" value="false" />
</bean>
</code>```

I am well aware that the prefix added by the template resolver ensures that there is not "circular view path" when the app uses this template resolver.

But then how I am supposed to test my app using Spring MVC test?

答:
When using @Controller annotation, you need @RequestMapping and @ResponseBody annotations.
Try again after adding annotation @ResponseBody

Body:
I have the following code in one of my controllers:

@Controller
@RequestMapping("/preference")
public class PreferenceController {

    @RequestMapping(method = RequestMethod.GET, produces = "text/html")
    public String preference() {
        return "preference";
    }
}

I am simply trying to test it using Spring MVC test as follows:

@ContextConfiguration
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class PreferenceControllerTest {

    @Autowired
    private WebApplicationContext ctx;

    private MockMvc mockMvc;
    @Before
    public void setup() {
        mockMvc = webAppContextSetup(ctx).build();
    }

    @Test
    public void circularViewPathIssue() throws Exception {
        mockMvc.perform(get("/preference"))
               .andDo(print());
    }
}

I am getting the following exception:

Circular view path [preference]: would dispatch back to the current
  handler URL [/preference] again. Check your ViewResolver setup! (Hint:
  This may be the result of an unspecified view, due to default view
  name generation.)

What I find strange is that it works fine when I load the "full" context configuration that includes the template and view resolvers as shown below:

<bean class="org.thymeleaf.templateresolver.ServletContextTemplateResolver" id="webTemplateResolver">
    <property name="prefix" value="WEB-INF/web-templates/" />
    <property name="suffix" value=".html" />
    <property name="templateMode" value="HTML5" />
    <property name="characterEncoding" value="UTF-8" />
    <property name="order" value="2" />
    <property name="cacheable" value="false" />
</bean>

I am well aware that the prefix added by the template resolver ensures that there is not "circular view path" when the app uses this template resolver.

But then how I am supposed to test my app using Spring MVC test?


问:
Invalid Token. Not accepting integers that start with 0
So I'm trying to make a check digit function, and embarrassingly, I've already run into a snag early on that I've been trying to search the problem for, but most of the explanations I've run into are unfortunately beyond my comprehension. I'm hoping someone could give me a specific run-down as to what my problem is right now

```<code>mam = []

def check_digit():
    a = int(input("Please enter your 10 digit book number"))
    b = str(a)
    for c in b:
        mam.append(c)
        print(c)

check_digit()
</code>```

Sorry about no set names for variables, I prefer coding this way even if it eventually gets awkward for others to read. Well anyway, every time I write in an integer which starts with 0, the Syntax error "Invalid token" appears and I don't know how to solve it. Could anyone help me? I would be grateful

Fixed. I really need to update Python, I'm running 2.7 at the moment.

raw_input solved the issue

答:
In Python, non-decimal numbers start with '0'. A decimal number cannot start with a '0'. Old-style octal numbers used to start with a '0', so '010' would be 8 in Python 2. Hex numbers started with '0x' and still do in Python 3. In Python 3, octal numbers now start with '0o'.
You're throwing the error because you're inputting a string and then running int() on it.  Don't do that. You can just check if the inputted string is all digits instead and make sure it's the right length.
Or, if you have your heart set on checking for a conversion to int as a decimal, you should strip off the leading zeros with value.lstrip('0') before the conversion.

Alternatively, you can just input the mam and then check if mam.isdigit():...
The .isdigit() method checks if the string consists only of numerical digits. This should be what you're looking for.

Body:
So I'm trying to make a check digit function, and embarrassingly, I've already run into a snag early on that I've been trying to search the problem for, but most of the explanations I've run into are unfortunately beyond my comprehension. I'm hoping someone could give me a specific run-down as to what my problem is right now

mam = []

def check_digit():
    a = int(input("Please enter your 10 digit book number"))
    b = str(a)
    for c in b:
        mam.append(c)
        print(c)

check_digit()

Sorry about no set names for variables, I prefer coding this way even if it eventually gets awkward for others to read. Well anyway, every time I write in an integer which starts with 0, the Syntax error "Invalid token" appears and I don't know how to solve it. Could anyone help me? I would be grateful

Fixed. I really need to update Python, I'm running 2.7 at the moment.

raw_input solved the issue


问:
logits doesn't have the proper shape in vgg16 model for x-ray classification
I got the same error as here.

I have two classes, so the rank of labels should be one --  which is correct-- and rank of logits should be two -- [bachsize, #classes]-- which is 4 here-- [? 3,3,2]. In that link mentioned using flatten() on convolutional layer(s). Which layers do you apply flatten() on? all the convolutions? or only the last one in the network -- I mean fc8 --.
Here's what I have in vgg.py:

```<code>with variable_scope.variable_scope(scope, 'vgg_16', [inputs]) as sc:
end_points_collection = sc.original_name_scope + '_end_points'
# Collect outputs for conv2d, fully_connected and max_pool2d.
with arg_scope(
    [layers.conv2d, layers_lib.fully_connected, layers_lib.max_pool2d],
    outputs_collections=end_points_collection):
  net = layers_lib.repeat(
      inputs, 2, layers.conv2d, 64, [3, 3], scope='conv1')
  net = layers_lib.max_pool2d(net, [2, 2], scope='pool1')
  net = layers_lib.repeat(net, 2, layers.conv2d, 128, [3, 3], scope='conv2')
  net = layers_lib.max_pool2d(net, [2, 2], scope='pool2')
  net = layers_lib.repeat(net, 3, layers.conv2d, 256, [3, 3], scope='conv3')
  net = layers_lib.max_pool2d(net, [2, 2], scope='pool3')
  net = layers_lib.repeat(net, 3, layers.conv2d, 512, [3, 3], scope='conv4')
  net = layers_lib.max_pool2d(net, [2, 2], scope='pool4')
  net = layers_lib.repeat(net, 3, layers.conv2d, 512, [3, 3], scope='conv5')
  net = layers_lib.max_pool2d(net, [2, 2], scope='pool5')
  # Use conv2d instead of fully_connected layers.
  net = layers.conv2d(net, 4096, [7, 7], padding='VALID', scope='fc6')
  net = layers_lib.dropout(
      net, dropout_keep_prob, is_training=is_training, scope='dropout6')
  net = layers.conv2d(net, 4096, [1, 1], scope='fc7')
  net = layers_lib.dropout(
      net, dropout_keep_prob, is_training=is_training, scope='dropout7')
  net = layers.conv2d(
      net,
      num_classes, [1, 1],
      activation_fn=None,
      normalizer_fn=None,
      scope='fc8')

  # Convert end_points_collection into a end_point dict.
  end_points = utils.convert_collection_to_dict(end_points_collection)
  if spatial_squeeze:
    net = array_ops.squeeze(net, [1, 2], name='fc8/squeezed')
    end_points[sc.name + '/fc8'] = net
  return net, end_points
</code>```

This is where I get the error in nn_ops.py:

```<code>  with ops.name_scope(name, "SparseSoftmaxCrossEntropyWithLogits",
                      [labels, logits]):
    labels = ops.convert_to_tensor(labels)
    logits = ops.convert_to_tensor(logits)

    precise_logits = math_ops.cast(logits, dtypes.float32) if (
        dtypes.as_dtype(logits.dtype) == dtypes.float16) else logits

    # Store label shape for result later.
    labels_static_shape = labels.get_shape()
    print(labels_static_shape)
    labels_shape = array_ops.shape(labels)

    print("labels_shape:", labels_shape)
    print("logits.get_shape().ndims:" ,(logits.get_shape().ndims))

    if logits.get_shape().ndims is not None and logits.get_shape().ndims == 0:
      raise ValueError("Logits cannot be scalars - received shape %s." %
                       logits.get_shape())
    if logits.get_shape().ndims is not None and (
        labels_static_shape.ndims is not None and
        labels_static_shape.ndims != logits.get_shape().ndims - 1):
        raise ValueError("Rank mismatch: Rank of labels (received %s) should "
                       "equal rank of logits minus 1 (received %s)." %
                       (labels_static_shape.ndims, logits.get_shape().ndims))
</code>```

And this is my error:

```<code>  File "/home/smolaei/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/ops/nn_ops.py", line 1695, in sparse_softmax_cross_entropy_with_logits
    (labels_static_shape.ndims, logits.get_shape().ndims))
ValueError: Rank mismatch: Rank of labels (received 1) should equal rank of logits minus 1 (received 4).
</code>```

Any recommendation on how to fix this?

答: Typically you'd flatten just before your output layers (your convolutions need non-flat input). See the TensorFlow MNIST model for example.</p>

Body:
I got the same error as here.

I have two classes, so the rank of labels should be one --  which is correct-- and rank of logits should be two -- [bachsize, #classes]-- which is 4 here-- [? 3,3,2]. In that link mentioned using flatten() on convolutional layer(s). Which layers do you apply flatten() on? all the convolutions? or only the last one in the network -- I mean fc8 --.
Here's what I have in vgg.py:

with variable_scope.variable_scope(scope, 'vgg_16', [inputs]) as sc:
end_points_collection = sc.original_name_scope + '_end_points'
# Collect outputs for conv2d, fully_connected and max_pool2d.
with arg_scope(
    [layers.conv2d, layers_lib.fully_connected, layers_lib.max_pool2d],
    outputs_collections=end_points_collection):
  net = layers_lib.repeat(
      inputs, 2, layers.conv2d, 64, [3, 3], scope='conv1')
  net = layers_lib.max_pool2d(net, [2, 2], scope='pool1')
  net = layers_lib.repeat(net, 2, layers.conv2d, 128, [3, 3], scope='conv2')
  net = layers_lib.max_pool2d(net, [2, 2], scope='pool2')
  net = layers_lib.repeat(net, 3, layers.conv2d, 256, [3, 3], scope='conv3')
  net = layers_lib.max_pool2d(net, [2, 2], scope='pool3')
  net = layers_lib.repeat(net, 3, layers.conv2d, 512, [3, 3], scope='conv4')
  net = layers_lib.max_pool2d(net, [2, 2], scope='pool4')
  net = layers_lib.repeat(net, 3, layers.conv2d, 512, [3, 3], scope='conv5')
  net = layers_lib.max_pool2d(net, [2, 2], scope='pool5')
  # Use conv2d instead of fully_connected layers.
  net = layers.conv2d(net, 4096, [7, 7], padding='VALID', scope='fc6')
  net = layers_lib.dropout(
      net, dropout_keep_prob, is_training=is_training, scope='dropout6')
  net = layers.conv2d(net, 4096, [1, 1], scope='fc7')
  net = layers_lib.dropout(
      net, dropout_keep_prob, is_training=is_training, scope='dropout7')
  net = layers.conv2d(
      net,
      num_classes, [1, 1],
      activation_fn=None,
      normalizer_fn=None,
      scope='fc8')

  # Convert end_points_collection into a end_point dict.
  end_points = utils.convert_collection_to_dict(end_points_collection)
  if spatial_squeeze:
    net = array_ops.squeeze(net, [1, 2], name='fc8/squeezed')
    end_points[sc.name + '/fc8'] = net
  return net, end_points

This is where I get the error in nn_ops.py:

  with ops.name_scope(name, "SparseSoftmaxCrossEntropyWithLogits",
                      [labels, logits]):
    labels = ops.convert_to_tensor(labels)
    logits = ops.convert_to_tensor(logits)

    precise_logits = math_ops.cast(logits, dtypes.float32) if (
        dtypes.as_dtype(logits.dtype) == dtypes.float16) else logits

    # Store label shape for result later.
    labels_static_shape = labels.get_shape()
    print(labels_static_shape)
    labels_shape = array_ops.shape(labels)

    print("labels_shape:", labels_shape)
    print("logits.get_shape().ndims:" ,(logits.get_shape().ndims))

    if logits.get_shape().ndims is not None and logits.get_shape().ndims == 0:
      raise ValueError("Logits cannot be scalars - received shape %s." %
                       logits.get_shape())
    if logits.get_shape().ndims is not None and (
        labels_static_shape.ndims is not None and
        labels_static_shape.ndims != logits.get_shape().ndims - 1):
        raise ValueError("Rank mismatch: Rank of labels (received %s) should "
                       "equal rank of logits minus 1 (received %s)." %
                       (labels_static_shape.ndims, logits.get_shape().ndims))

And this is my error:

  File "/home/smolaei/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/ops/nn_ops.py", line 1695, in sparse_softmax_cross_entropy_with_logits
    (labels_static_shape.ndims, logits.get_shape().ndims))
ValueError: Rank mismatch: Rank of labels (received 1) should equal rank of logits minus 1 (received 4).

Any recommendation on how to fix this?


问:
Blank page with vue-router with history mode and production
I'm new with vue and I've the next error. I build a little project with the next template https://github.com/vuejs-templates/webpack with default configuration.

I've added vue-router and it works fine when I'm in develop mode, but when I build production mode and use, it show a blank page.

If I remove history mode of configuration, it works. Any suggestion?

Thanks.

答:
@bbsimonbb, I test the fallback but it didn't work.

The problem was with configuration of Router, specifically the property base. By default is '/' but you should configure with the base of your web app. You can read more in more detail here

Ex: http://www.mywebsite.com/myapp/ => base: '/myapp/'

The path where I've the file on I configure the Router is /src/router/index.js

I hope it helps someone to avoid time.


问:
How to animate ScrollTop with @angular/animations?
I'm trying to replicate this animation from Material.io:

To just navigate the height like the click on the first card in the example above is simple. Just animate height attribute. The problem is with the click on the second card where it then pushes the other cards away.

One solution to this is to use scroll to emulate the effect that things get pushed away. So when you click on the item, it both makes it taller by animating the height, but also scroll the view at the same time.

My problem:
I can't seem to figure out how to animate scrolls with @angular/animations.
I can't use style({ scrollTop: 100 }), it only allows for CSS attributes according to the documentation.

How do I achieve this? It would be nice if I could do it as part of the animate() animation for maintenance reasons (To keep the whole animation in 1 location in the code), but if it's only possible with a separate method I guess that would be acceptable as well.

答:
I managed to create this, using three Angular animations states : small, big and normal, corresponding to the height of the div :

animations.ts

Here, I used one state variable per div as an example, and I set the each of these states to normal by default.
Then, depending on which div I click on, I toggle the states according to what we want to happen : making the div we click on bigger and the others smaller

```<code>export const expand = [
  trigger('expand', [
    state('big', style({
      'height': '200px'
    })),
    state('normal', style({
      'height': '100px'
    })),
    state('small', style({
      'height': '50px'
    })),
    transition('* => *', [group([
      animate(1000)
    ]
    )])
  ]),
]
</code>```

app.component.ts

```<code>import { expand } from './animations';

@Component({
  ...
  animations: [expand]
})
export class AppComponent implements OnInit {
  expandState1 = 'normal';
  expandState2 = 'normal';
  expandState3 = 'normal';
  expandState4 = 'normal';
  expandState5 = 'normal';

  ngOnInit() {
    this.resetStates();
  }

  resetStates() {
    this.expandState1 = 'normal';
    this.expandState2 = 'normal';
    this.expandState3 = 'normal';
    this.expandState4 = 'normal';
    this.expandState5 = 'normal';
  }

  toggleShowDiv(divName: string) {
    if (divName === 'div1') {
      if (this.expandState1 === 'normal' || this.expandState1 === 'small') {
        this.setToBig([1]);
        this.setToSmall([2, 3, 4, 5]);
      } else if (this.expandState1 === 'big' || this.expandState1 === 'small') {
        this.resetStates();
      }
    } else if (divName === 'div2') {
      if (this.expandState2 === 'normal' || this.expandState2 === 'small') {
        this.setToBig([2]);
        this.setToSmall([1, 3, 4, 5]);
      } else if (this.expandState2 === 'big') {
        this.resetStates();
      }
    } else if (divName === 'div3') {
      if (this.expandState3 === 'normal' || this.expandState3 === 'small') {
        this.setToBig([3]);
        this.setToSmall([1, 2, 4, 5]);
      } else if (this.expandState3 === 'big') {
        this.resetStates();
      }
    } else if (divName === 'div4') {
      if (this.expandState4 === 'normal' || this.expandState4 === 'small') {
        this.setToBig([4]);
        this.setToSmall([1, 2, 3, 5]);
      } else if (this.expandState4 === 'big') {
        this.resetStates();
      }
    } else if (divName === 'div5') {
      if (this.expandState5 === 'normal' || this.expandState5 === 'small') {
        this.setToBig([5]);
        this.setToSmall([1, 2, 3, 4]);
      } else if (this.expandState5 === 'big') {
        this.resetStates();
      }
    }
  }

  setToSmall(choices: any) {
    for (let i = 0; i < choices.length; i++) {
      switch (choices[i]) {
        case 1:
          this.expandState1 = 'small';
          break;
        case 2:
          this.expandState2 = 'small';
          break;
        case 3:
          this.expandState3 = 'small';
          break;
        case 4:
          this.expandState4 = 'small';
          break;
        case 5:
          this.expandState5 = 'small';
          break;
        default:
          break;
      }
    }
  }

  setToBig(choices: any) {
    for (let i = 0; i < choices.length; i++) {
      switch (choices[i]) {
        case 1:
          this.expandState1 = 'big';
          break;
        case 2:
          this.expandState2 = 'big';
          break;
        case 3:
          this.expandState3 = 'big';
          break;
        case 4:
          this.expandState4 = 'big';
          break;
        case 5:
          this.expandState5 = 'big';
          break;
        default:
          break;
      }
    }
  }
}
</code>```

And here is the corresponding template :

Each div has the reference to the animation trigger [@expand] and its state.

```<code><div class="wrapper scrollableDiv">
  <div [@expand]="expandState1" (click)="toggleShowDiv('div1')" class="content divA">THIS IS CONTENT DIV 1</div>
  <div [@expand]="expandState2" (click)="toggleShowDiv('div2')" class="content divA">THIS IS CONTENT DIV 2</div>
  <div [@expand]="expandState3" (click)="toggleShowDiv('div3')" class="content divA">THIS IS CONTENT DIV 3</div>
  <div [@expand]="expandState4" (click)="toggleShowDiv('div4')" class="content divA">THIS IS CONTENT DIV 4</div>
  <div [@expand]="expandState5" (click)="toggleShowDiv('div5')" class="content divA">THIS IS CONTENT DIV 5</div>
</div>
</code>```

Here is a StackBlitz example I made for this : https://stackblitz.com/edit/angular-t47iyy

Body:
I managed to create this, using three Angular animations states : small, big and normal, corresponding to the height of the div :

animations.ts

Here, I used one state variable per div as an example, and I set the each of these states to normal by default.
Then, depending on which div I click on, I toggle the states according to what we want to happen : making the div we click on bigger and the others smaller

export const expand = [
  trigger('expand', [
    state('big', style({
      'height': '200px'
    })),
    state('normal', style({
      'height': '100px'
    })),
    state('small', style({
      'height': '50px'
    })),
    transition('* => *', [group([
      animate(1000)
    ]
    )])
  ]),
]

app.component.ts

import { expand } from './animations';

@Component({
  ...
  animations: [expand]
})
export class AppComponent implements OnInit {
  expandState1 = 'normal';
  expandState2 = 'normal';
  expandState3 = 'normal';
  expandState4 = 'normal';
  expandState5 = 'normal';

  ngOnInit() {
    this.resetStates();
  }

  resetStates() {
    this.expandState1 = 'normal';
    this.expandState2 = 'normal';
    this.expandState3 = 'normal';
    this.expandState4 = 'normal';
    this.expandState5 = 'normal';
  }

  toggleShowDiv(divName: string) {
    if (divName === 'div1') {
      if (this.expandState1 === 'normal' || this.expandState1 === 'small') {
        this.setToBig([1]);
        this.setToSmall([2, 3, 4, 5]);
      } else if (this.expandState1 === 'big' || this.expandState1 === 'small') {
        this.resetStates();
      }
    } else if (divName === 'div2') {
      if (this.expandState2 === 'normal' || this.expandState2 === 'small') {
        this.setToBig([2]);
        this.setToSmall([1, 3, 4, 5]);
      } else if (this.expandState2 === 'big') {
        this.resetStates();
      }
    } else if (divName === 'div3') {
      if (this.expandState3 === 'normal' || this.expandState3 === 'small') {
        this.setToBig([3]);
        this.setToSmall([1, 2, 4, 5]);
      } else if (this.expandState3 === 'big') {
        this.resetStates();
      }
    } else if (divName === 'div4') {
      if (this.expandState4 === 'normal' || this.expandState4 === 'small') {
        this.setToBig([4]);
        this.setToSmall([1, 2, 3, 5]);
      } else if (this.expandState4 === 'big') {
        this.resetStates();
      }
    } else if (divName === 'div5') {
      if (this.expandState5 === 'normal' || this.expandState5 === 'small') {
        this.setToBig([5]);
        this.setToSmall([1, 2, 3, 4]);
      } else if (this.expandState5 === 'big') {
        this.resetStates();
      }
    }
  }

  setToSmall(choices: any) {
    for (let i = 0; i < choices.length; i++) {
      switch (choices[i]) {
        case 1:
          this.expandState1 = 'small';
          break;
        case 2:
          this.expandState2 = 'small';
          break;
        case 3:
          this.expandState3 = 'small';
          break;
        case 4:
          this.expandState4 = 'small';
          break;
        case 5:
          this.expandState5 = 'small';
          break;
        default:
          break;
      }
    }
  }

  setToBig(choices: any) {
    for (let i = 0; i < choices.length; i++) {
      switch (choices[i]) {
        case 1:
          this.expandState1 = 'big';
          break;
        case 2:
          this.expandState2 = 'big';
          break;
        case 3:
          this.expandState3 = 'big';
          break;
        case 4:
          this.expandState4 = 'big';
          break;
        case 5:
          this.expandState5 = 'big';
          break;
        default:
          break;
      }
    }
  }
}

And here is the corresponding template :

Each div has the reference to the animation trigger [@expand] and its state.

<div class="wrapper scrollableDiv">
  <div [@expand]="expandState1" (click)="toggleShowDiv('div1')" class="content divA">THIS IS CONTENT DIV 1</div>
  <div [@expand]="expandState2" (click)="toggleShowDiv('div2')" class="content divA">THIS IS CONTENT DIV 2</div>
  <div [@expand]="expandState3" (click)="toggleShowDiv('div3')" class="content divA">THIS IS CONTENT DIV 3</div>
  <div [@expand]="expandState4" (click)="toggleShowDiv('div4')" class="content divA">THIS IS CONTENT DIV 4</div>
  <div [@expand]="expandState5" (click)="toggleShowDiv('div5')" class="content divA">THIS IS CONTENT DIV 5</div>
</div>

Here is a StackBlitz example I made for this : https://stackblitz.com/edit/angular-t47iyy


问:
mpirun on os X
Is there a way to run a local mpi job locally on os X leopard(10.5.6) with more than 62 processes.  When I run the job with 62 processes, it dies

```<code>$mpirun -np 62 a.out
mpirun noticed that job rank 0 with PID 0 on node Macintosh-001D4F4BC6BC.private exited on signal 15 (Terminated).
60 additional processes aborted (not shown)
</code>```

and when I run it with 61 processes it runs fine.

答: In response to my comment, I did some googling and I suspect that this is caused by a resource limit set by the OS. Also, the vicinity of the failure to a multiple 2 is suspicious. My best guess is that something in the mpi library (MPI_Send maybe) is spawning additional processes, which exceed the limit of 266 (see ulimit -a).</p>

OwnerDisplayName: Milhous

Title: mpirun on os X

Body:
Is there a way to run a local mpi job locally on os X leopard(10.5.6) with more than 62 processes.  When I run the job with 62 processes, it dies

$mpirun -np 62 a.out
mpirun noticed that job rank 0 with PID 0 on node Macintosh-001D4F4BC6BC.private exited on signal 15 (Terminated).
60 additional processes aborted (not shown)

and when I run it with 61 processes it runs fine.

OwnerDisplayName: Dana the Sane


问:
Move a div using keypresses and jquery?
Alright, so I'm trying to make a simple script that moves down a div when I press 's' but it's not firing at all. I got Jquery installed, and the error-console in FF isn't saying anything. Can someone tell me what I'm doing wrong?

http://prime.programming-designs.com/designs/map/

答:
I suggest you use the jquery.hotkeys extension to bind to the key events:
https://github.com/jeresig/jquery.hotkeys</p>

Title: Move a div using keypresses and jquery?


问:
Nested For Each Statement
Good Morning All,

I'm using the Advanced Example from the VBA-JSON Parser to load JSON files into excel. It works fine, but I'd like to change a bit of code to iterate through a string array instead of spelling each item out.

Here's the part I'd like to change:

```<code>Dim Value As Dictionary
Dim i As Long

i = 0
For Each Value In Parsed("values")
  Values(i, 0) = Value("a")
  Values(i, 1) = Value("b")
  Values(i, 2) = Value("c")
  i = i + 1
Next Value

Sheets("example").Range(Cells(1, 1), Cells(Parsed("values").Count, 3)) = Values
</code>```

Instead of spelling out each value ("a", "b", "c"), I'd like it to just run through each item I have in my string array while it's iterating through each value in the parsed list.

This is the string array I have:

```<code>Dim ParentArray As Variant

ParentArray = Array("a", "b", "c", "d", "e")
</code>```

I imagine it's something like this, but I'm not sure how to make it work...

```<code>i = 0
For Each Value In Parsed(parent)
    n = 1
        For Each ArrItem In ParentArray
            ArrItem = (ParentArray(1, n))
            Values(i, n - 1) = Value(ArrItem)
            n = n + 1
        Next ArrItem
    i = i + 1
Next Value

Sheets(parent).Range(Cells(2, 1), Cells(Parsed(parent).Count, ColCount)) = Values
</code>```

Any help would be greatly appreciated.

Thanks,

Phillip

答:
I think that you have it correct, it's just a matter of syntax:</p>

```<code>For Each Value In Parsed(parent)
    n = 1
        For j = LBound(ParentArray) to UBound(ParentArray)
            Values(i, n - 1) = Value(ParentArray(j))
            n = n + 1
        Next j
    i = i + 1
Next Value
</code>```

Title: Nested For Each Statement

Body:
Good Morning All,

I'm using the Advanced Example from the VBA-JSON Parser to load JSON files into excel. It works fine, but I'd like to change a bit of code to iterate through a string array instead of spelling each item out.

Here's the part I'd like to change:

Dim Value As Dictionary
Dim i As Long

i = 0
For Each Value In Parsed("values")
  Values(i, 0) = Value("a")
  Values(i, 1) = Value("b")
  Values(i, 2) = Value("c")
  i = i + 1
Next Value

Sheets("example").Range(Cells(1, 1), Cells(Parsed("values").Count, 3)) = Values

Instead of spelling out each value ("a", "b", "c"), I'd like it to just run through each item I have in my string array while it's iterating through each value in the parsed list.

This is the string array I have:

Dim ParentArray As Variant

ParentArray = Array("a", "b", "c", "d", "e")

I imagine it's something like this, but I'm not sure how to make it work...

i = 0
For Each Value In Parsed(parent)
    n = 1
        For Each ArrItem In ParentArray
            ArrItem = (ParentArray(1, n))
            Values(i, n - 1) = Value(ArrItem)
            n = n + 1
        Next ArrItem
    i = i + 1
Next Value

Sheets(parent).Range(Cells(2, 1), Cells(Parsed(parent).Count, ColCount)) = Values

Any help would be greatly appreciated.

Thanks,

Phillip

Body:
I think that you have it correct, it's just a matter of syntax:

For Each Value In Parsed(parent)
    n = 1
        For j = LBound(ParentArray) to UBound(ParentArray)
            Values(i, n - 1) = Value(ParentArray(j))
            n = n + 1
        Next j
    i = i + 1
Next Value


问:
I am stuck on my Java homework Parsing Strings
I am somewhat lost on what to do.

There are 4 parts.

Prompt the user for a string that contains two strings separated by a comma.

Report an error if the input string does not contain a comma. Continue to prompt until a valid string is entered. Note: If the input contains a comma, then assume that the input also contains two strings.

Extract the two words from the input string and remove any spaces. Store the strings in two separate variables and output the strings.

Using a loop, extend the program to handle multiple lines of input. Continue until the user enters q to quit.

Final outcome should print out as follows:

```<code>Enter input string: Jill, Allen
First word: Jill
Second word: Allen

Enter input string: Golden , Monkey
First word: Golden
Second word: Monkey

Enter input string: Washington,DC
First word: Washington
Second word: DC

Enter input string: q
</code>```

I've figured out everything out but can't figure out the second part. I don't exactly know how to do the code for does not contain comma.

Here's my code:

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

public class ParseStrings {

public static void main(String[] args) {
    Scanner scnr = new Scanner(System.in);
    String lineString = "";
    int commaLocation = 0;
    String firstWord = "";
    String secondWord = "";
    boolean inputDone = false;

    while (!inputDone) {
        System.out.println("Enter input string: ");
        lineString = scnr.nextLine();

        if (lineString.equals("q")) {
            inputDone = true;
        }

        else {
        commaLocation = lineString.indexOf(',');
        firstWord = lineString.substring(0, commaLocation);
        secondWord = lineString.substring(commaLocation + 1, lineString.length());

        System.out.println("First word: " + firstWord);
        System.out.println("Second word:" + secondWord);
        System.out.println();
        System.out.println();
        }
    }

    return;
    }
}
</code>```

答:
Let's have a look at the line:

```<code>commaLocation = lineString.indexOf(',');
</code>```

in case there is no comma, .indexOf() returns -1 - you can take advantage of it and add an if condition right after this line and handle this case as well!

Body:
I am somewhat lost on what to do.

There are 4 parts.

Prompt the user for a string that contains two strings separated by a comma.

Report an error if the input string does not contain a comma. Continue to prompt until a valid string is entered. Note: If the input contains a comma, then assume that the input also contains two strings.

Extract the two words from the input string and remove any spaces. Store the strings in two separate variables and output the strings.

Using a loop, extend the program to handle multiple lines of input. Continue until the user enters q to quit.

Final outcome should print out as follows:

Enter input string: Jill, Allen
First word: Jill
Second word: Allen

Enter input string: Golden , Monkey
First word: Golden
Second word: Monkey

Enter input string: Washington,DC
First word: Washington
Second word: DC

Enter input string: q

I've figured out everything out but can't figure out the second part. I don't exactly know how to do the code for does not contain comma.

Here's my code:

import java.util.Scanner;

public class ParseStrings {

public static void main(String[] args) {
    Scanner scnr = new Scanner(System.in);
    String lineString = "";
    int commaLocation = 0;
    String firstWord = "";
    String secondWord = "";
    boolean inputDone = false;

    while (!inputDone) {
        System.out.println("Enter input string: ");
        lineString = scnr.nextLine();

        if (lineString.equals("q")) {
            inputDone = true;
        }

        else {
        commaLocation = lineString.indexOf(',');
        firstWord = lineString.substring(0, commaLocation);
        secondWord = lineString.substring(commaLocation + 1, lineString.length());

        System.out.println("First word: " + firstWord);
        System.out.println("Second word:" + secondWord);
        System.out.println();
        System.out.println();
        }
    }

    return;
    }
}

Body:
Let's have a look at the line:

commaLocation = lineString.indexOf(',');

in case there is no comma, .indexOf() returns -1 - you can take advantage of it and add an if condition right after this line and handle this case as well!


问:
Trying get titles from multiple pages in beautifulsoup
I am trying to get all blog titles from every page on a blog but so far am only able to produce output from the last page on that blog</p>

```<code>from urllib.request import urlopen
from bs4 import BeautifulSoup

base_url = 'http://www.madame-love.com'

n = 10
for i in range(2, n+1):
    html = urlopen(base_url + "/page/%d" % i)
    page = BeautifulSoup(html.read(), 'html.parser')

for titles in page.findAll('h2'):
    print(titles.string)
</code>```

答:
Try this. It will give you all the titles across different pages:</p>

```<code>import requests
from bs4 import BeautifulSoup

base_url = 'http://www.madame-love.com/page/{}/'
for link in [base_url.format(page) for page in range(1,5)]:  #just input the highest page number in place of 5
    res = requests.get(link)
    soup = BeautifulSoup(res.text, 'lxml')
    for titles in soup.select('h2.entry-title a'):
        print(titles.text)
</code>```

Body:
I am trying to get all blog titles from every page on a blog but so far am only able to produce output from the last page on that blog

from urllib.request import urlopen
from bs4 import BeautifulSoup

base_url = 'http://www.madame-love.com'

n = 10
for i in range(2, n+1):
    html = urlopen(base_url + "/page/%d" % i)
    page = BeautifulSoup(html.read(), 'html.parser')

for titles in page.findAll('h2'):
    print(titles.string)

Body:
Try this. It will give you all the titles across different pages:

import requests
from bs4 import BeautifulSoup

base_url = 'http://www.madame-love.com/page/{}/'
for link in [base_url.format(page) for page in range(1,5)]:  #just input the highest page number in place of 5
    res = requests.get(link)
    soup = BeautifulSoup(res.text, 'lxml')
    for titles in soup.select('h2.entry-title a'):
        print(titles.text)


问:
Multiplying parenthesis to get a polynomial in python
I was asked to do the newton polynomial interpolation and I was able to write the main code.
https://en.wikipedia.org/wiki/Newton_polynomial
But there is still one small thing that I am not able to get around since a couple of days, after reading I found a way to do it using Sympy, but I am not allowed to use anything other than basic numpy.
Now my problem is that I trying to multiply something like this

p(x)=j(x-q)(x-w)(x-e)+k(x-w)(x-e)+l(x-e)+d

to get this p(x)=ax³+bx²+cx+d , so I amlooking for the polynomial coefficients a,b,c,d

for example:

p(x)=5-7(x+1)+9(x+1)(x)-7(x+1)(x)(x-1)=-7x³+9x²+9x-2

of course I am looking for the general case, not only for ploynomials from third degree.
Any tip would be much appreciated, I am really stuck at this since a couple of days.
and Sorry for the sloppy writing of notation, but it seems stackoverflow doesn't accept latex and I am not able to post a picture because I don't have rhe required reputation. (if there is other solutuions to post it properly please tell me and I'll just post it again)

Thanks in advance :)

答:
Using numpy, we have access to the poly1d object. With that, j(x-q)(x-w)(x-e)+k(x-w)(x-e)+l(x-e)+d is equivalent to:

```<code>In [ ]: j, q, w, e, k, w, l, d = range(1, 9)
   ...: poly1 = j*np.poly1d([-q, -w, -e], r=1)
   ...: poly2 = k*np.poly1d([-w, -e], r=0)
   ...: poly3 = l*np.poly1d([-e])
   ...: poly = poly1 + poly2 + poly3 + d
   ...: print(poly)
   3      2
1 x + 12 x + 14 x + 8
</code>```

Body:
Using numpy, we have access to the poly1d object. With that, j(x-q)(x-w)(x-e)+k(x-w)(x-e)+l(x-e)+d is equivalent to:

In [ ]: j, q, w, e, k, w, l, d = range(1, 9)
   ...: poly1 = j*np.poly1d([-q, -w, -e], r=1)
   ...: poly2 = k*np.poly1d([-w, -e], r=0)
   ...: poly3 = l*np.poly1d([-e])
   ...: poly = poly1 + poly2 + poly3 + d
   ...: print(poly)
   3      2
1 x + 12 x + 14 x + 8


问:
string.IndexOf search for whole word match
I am seeking a way to search a string for an exact match or whole word match.  RegEx.Match and RegEx.IsMatch don't seem to get me where I want to be.
Consider the following scenario:

```<code>namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "SUBTOTAL 34.37 TAX TOTAL 37.43";
            int indx = str.IndexOf("TOTAL");
            string amount = str.Substring(indx + "TOTAL".Length, 10);
            string strAmount = Regex.Replace(amount, "[^.0-9]", "");

            Console.WriteLine(strAmount);
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
    }
}
</code>```

The output of the above code is:

```<code>// 34.37
// Press any key to continue...
</code>```

The problem is, I don't want SUBTOTAL, but IndexOf finds the first occurrence of the word TOTAL which is in SUBTOTAL which then yields the incorrect value of 34.37.

So the question is, is there a way to force IndexOf to find only an exact match or is there another way to force that exact whole word match so that I can find the index of that exact match and then perform some useful function with it. RegEx.IsMatch and RegEx.Match are, as far as I can tell, simply boolean searches.  In this case, it isn't enough to just know the exact match exists.  I need to know where it exists in the string.

Any advice would be appreciated.

答:
My method is faster than the accepted answer because it does not use Regex.</p>

```<code>string str = "SUBTOTAL 34.37 TAX TOTAL 37.43";
var indx = str.IndexOfWholeWord("TOTAL");

public static int IndexOfWholeWord(this string str, string word)
{
    for (int j = 0; j < str.Length &&
        (j = str.IndexOf(word, j, StringComparison.Ordinal)) >= 0; j++)
        if ((j == 0 || !char.IsLetterOrDigit(str, j - 1)) &&
            (j + word.Length == str.Length || !char.IsLetterOrDigit(str, j + word.Length)))
            return j;
    return -1;
}
</code>```

Body:
I am seeking a way to search a string for an exact match or whole word match.  RegEx.Match and RegEx.IsMatch don't seem to get me where I want to be.
Consider the following scenario:

namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "SUBTOTAL 34.37 TAX TOTAL 37.43";
            int indx = str.IndexOf("TOTAL");
            string amount = str.Substring(indx + "TOTAL".Length, 10);
            string strAmount = Regex.Replace(amount, "[^.0-9]", "");

            Console.WriteLine(strAmount);
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
    }
}

The output of the above code is:

// 34.37
// Press any key to continue...

The problem is, I don't want SUBTOTAL, but IndexOf finds the first occurrence of the word TOTAL which is in SUBTOTAL which then yields the incorrect value of 34.37.

So the question is, is there a way to force IndexOf to find only an exact match or is there another way to force that exact whole word match so that I can find the index of that exact match and then perform some useful function with it. RegEx.IsMatch and RegEx.Match are, as far as I can tell, simply boolean searches.  In this case, it isn't enough to just know the exact match exists.  I need to know where it exists in the string.

Any advice would be appreciated.

Body:
My method is faster than the accepted answer because it does not use Regex.

string str = "SUBTOTAL 34.37 TAX TOTAL 37.43";
var indx = str.IndexOfWholeWord("TOTAL");

public static int IndexOfWholeWord(this string str, string word)
{
    for (int j = 0; j < str.Length &&
        (j = str.IndexOf(word, j, StringComparison.Ordinal)) >= 0; j++)
        if ((j == 0 || !char.IsLetterOrDigit(str, j - 1)) &&
            (j + word.Length == str.Length || !char.IsLetterOrDigit(str, j + word.Length)))
            return j;
    return -1;
}


问:
Find by association (Datamapper)
I've got two models that look like this

```<code>class Stage
    include DataMapper::Resource
    property :id, Serial
    belongs_to :staff
end

class Staff
  include DataMapper::Resource
  property :id, String, :key => true
  property  :full_name, String
  property  :email, String
  has n, :stages
end
</code>```

I'm trying to find all Stages that have a specific Staff member assigned. I've tried     @stages = Stage.all(Stage.Staff => 'TM')

What am I doing wrong?

答:
Actually you can use string keys in datamapper like this:

```<code>Stage.all('staff.id' => 'TM')
</code>```

or

```<code>Stage.all('staff.name.like' => 'Ted%')
</code>```

You can mix and match with properties in that model as well:

```<code>Stage.all('staff.name.like' => 'Ted%', 'id.gte' => 5 )
</code>```

That'll get all of the Stages belonging to people whose names start with 'Ted' and have an id greater than or equal to 5.

Title: Find by association (Datamapper)

Body:
I've got two models that look like this

class Stage
    include DataMapper::Resource
    property :id, Serial
    belongs_to :staff
end

class Staff
  include DataMapper::Resource
  property :id, String, :key => true
  property  :full_name, String
  property  :email, String
  has n, :stages
end

I'm trying to find all Stages that have a specific Staff member assigned. I've tried     @stages = Stage.all(Stage.Staff => 'TM')

What am I doing wrong?

Body:
Actually you can use string keys in datamapper like this:

Stage.all('staff.id' => 'TM')

or

Stage.all('staff.name.like' => 'Ted%')

You can mix and match with properties in that model as well:

Stage.all('staff.name.like' => 'Ted%', 'id.gte' => 5 )

That'll get all of the Stages belonging to people whose names start with 'Ted' and have an id greater than or equal to 5.


问:
Apache Redirect // to no //
An email went out with the wrong link (https://www.digitalmarketer.com/digital-marketing/content-marketing-strategy//) and we need to redirect the // to (https://www.digitalmarketer.com/digital-marketing/content-marketing-strategy/) but no matter what I try, the redirect isn't working.

They also want it to be redirected to always have https:///www at the beginning and to never have index.html at the end, so already in the .htaccess file I have:

```<code>RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteRule ^content\-marketing\-strategy/index\.html$ /digital-marketing/content-marketing-strategy/? [L,R=301]
</code>```

I've tried adding a new RewriteRule, but this won't work:

```<code>RewriteRule ^content\-marketing\-strategy//$ /digital-marketing/content-marketing-strategy/? [L,R=301]
</code>```

I'm very new to Apache and redirects so any help is much appreciated! Thank you!

Edit: Of note, this is in an .htaccess file inside of the digital-marketing folder (https://www.digitalmarketer.com/digital-marketing/.htaccess) which was done so all the above rules would only apply to the digital-marketing folder.

答:
You can write a wildcard expression to remove trailing slashes. The below will match any HTTP or HTTPS URL that trails in a forward slash, and remove all trailing forward slashes from that URL:

RewriteRule ^(.*)/+$ $1 [R=301,L]```

And more using 301 redirects, see more here: Best Practice: 301 Redirect HTTP to HTTPS (Standard Domain)

Good luck!

Title: Apache Redirect // to no //

Body:
An email went out with the wrong link (https://www.digitalmarketer.com/digital-marketing/content-marketing-strategy//) and we need to redirect the // to (https://www.digitalmarketer.com/digital-marketing/content-marketing-strategy/) but no matter what I try, the redirect isn't working.

They also want it to be redirected to always have https:///www at the beginning and to never have index.html at the end, so already in the .htaccess file I have:

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteRule ^content\-marketing\-strategy/index\.html$ /digital-marketing/content-marketing-strategy/? [L,R=301]

I've tried adding a new RewriteRule, but this won't work:

RewriteRule ^content\-marketing\-strategy//$ /digital-marketing/content-marketing-strategy/? [L,R=301]

I'm very new to Apache and redirects so any help is much appreciated! Thank you!

Edit: Of note, this is in an .htaccess file inside of the digital-marketing folder (https://www.digitalmarketer.com/digital-marketing/.htaccess) which was done so all the above rules would only apply to the digital-marketing folder.

Body:
You can write a wildcard expression to remove trailing slashes. The below will match any HTTP or HTTPS URL that trails in a forward slash, and remove all trailing forward slashes from that URL:

RewriteRule ^(.*)/+$ $1 [R=301,L]

And more using 301 redirects, see more here: Best Practice: 301 Redirect HTTP to HTTPS (Standard Domain)

Good luck!


问:
Can full text search thesauruses be used with SQL Server Azure?
I have a codebase that I'm trying to deploy against an Azure instance of SQL Server. The application makes use of full text search's thesauruses. That is, it makes queries using

FORMSOF(THESAURUS, \"{0}\")

According to this, Azure SQL Server has thesauruses. But I've read conflicting things.

When I actually attempt this, I get the following error when the query tries to run:

Both the thesaurus file for lcid '1033' and the global thesaurus could not be loaded

I have checked that full text search is successfully installed on the server.

Is this even possible with Azure SQL Server?

答:
The thesaurus feature of Full-Text Search is not supported on Azure SQL Database since the feature involves access to the file system and changes registry settings and files, and that is not allowed on Azure SQL Database. That is the answer I received from 2 Azure SQL Database managers today.

You may need to create an Azure VM with SQL Server installed to make use of the Thesaurus feature on Azure.

The article you shared with us will be updated to reflect the answer provided by SQL Azure team.

Thank you for your patience.


问:
Theme child on wordpress
I'm new on wordpress and I have readed about childs themes.

My question is, Is that neccessary that I create my self child theme or can I use other theme child created ? that's to say, if I use a child theme created for other person, that theme will not change that I do it?

答:
The way a child theme works is that it overrides the default settings of your chosen theme. So you only have to allow for the parts of the theme that you want to make your own.

As long as a child theme created for someone else is based on YOUR main theme, then you could use someone else's child theme.

For example, if someone has a child theme that works for Wordpress 2017, you can upload and modify that for your own use, for example to change the css or create your own header and footer files (usually named header.php and footer.php). These are the things I do most often.

If you don't already have a child theme for your chosen theme, though, it is best that you create one yourself. It is quite straightforward, all you have to do as a minimum is create a child theme folder with a style.css in the correct format and a functions.php file in the same folder using these instructions https://codex.wordpress.org/Child_Themes

If all you want to do is play with color and fonts, you might find it easiest to just use the Wordpress Theme Customizer. These changes will be maintained during upgrades in a custom.css file (or equivalent) so you shouldn't need a child theme.

Hope this helps

Title: Theme child on wordpress


问:
PHP returning a string with the first char of every words in lowercase
There is already a function in PHP called ucwords which does just the opposite of what i need.

Is there such php library called lcwords? where instead of capitalizing the first of every words it converts them to lower case.

Thanks.

答:
I know the topic is ancient, but the problem still persist which is a shame (no lcwords() even now).

Here is lcwords() to lowercase each first letter of each word.

Simply put: this solution is universal and any punctuation should not be a problem for it. Of course, you pay you price for it :)

```<code>
    /**
     * Lowercase the first character of each word in a string
     *
     * @param  string $string     The input string.
     * @param string $delimiters The optional delimiters contains the word separator characters (regular expression)
     *
     * @return string             Returns the modified string.
     */
    function lcwords($string, $delimiters = "\W_\t\r\n\f\v") {
        $string = preg_replace_callback("/([$delimiters])(\w)/", function($match) {
            return $match[1].lcfirst($match[2]);
        }, $string);

        return lcfirst($string); // Uppercase first char if it's the beginning of the line
    }

    // Here is a couple of result examples:

    echo lcwords("/SuperModule/ActionStyle/Controller.php").PHP_EOL;
    // result:    /superModule/actionStyle/controller.php

    echo lcwords("SEPARATED\tBY TABS\nAND\rSPACES").PHP_EOL;
    // result:    sEPARATED  bY tABS  aND  sPACES

    echo lcwords("HELLO").PHP_EOL;
    // result:    hELLO

    echo lcwords("HEELO HOW-ARE_YOU").PHP_EOL;
    // result:    hEELO hOW-aRE_yOU

    echo lcwords("SEPARATED\tBY TABS\nAND\rSPACES").PHP_EOL;
    // result:    sEPARATED  bY tABS  aND  sPACES
</code>```

/([$delimiters])(\w)/ - Pattern have two groups: search for 1 non word character followed by 1 word character. Then word character will be uppercased in a callback. So only selected set of characters are getting updated - minimum changes of the content.

Body:
I know the topic is ancient, but the problem still persist which is a shame (no lcwords() even now).

Here is lcwords() to lowercase each first letter of each word.

Simply put: this solution is universal and any punctuation should not be a problem for it. Of course, you pay you price for it :)

    /**
     * Lowercase the first character of each word in a string
     *
     * @param  string $string     The input string.
     * @param string $delimiters The optional delimiters contains the word separator characters (regular expression)
     *
     * @return string             Returns the modified string.
     */
    function lcwords($string, $delimiters = "\W_\t\r\n\f\v") {
        $string = preg_replace_callback("/([$delimiters])(\w)/", function($match) {
            return $match[1].lcfirst($match[2]);
        }, $string);

        return lcfirst($string); // Uppercase first char if it's the beginning of the line
    }

    // Here is a couple of result examples:

    echo lcwords("/SuperModule/ActionStyle/Controller.php").PHP_EOL;
    // result:    /superModule/actionStyle/controller.php

    echo lcwords("SEPARATED\tBY TABS\nAND\rSPACES").PHP_EOL;
    // result:    sEPARATED  bY tABS  aND  sPACES

    echo lcwords("HELLO").PHP_EOL;
    // result:    hELLO

    echo lcwords("HEELO HOW-ARE_YOU").PHP_EOL;
    // result:    hEELO hOW-aRE_yOU

    echo lcwords("SEPARATED\tBY TABS\nAND\rSPACES").PHP_EOL;
    // result:    sEPARATED  bY tABS  aND  sPACES

/([$delimiters])(\w)/ - Pattern have two groups: search for 1 non word character followed by 1 word character. Then word character will be uppercased in a callback. So only selected set of characters are getting updated - minimum changes of the content.


问:
Tomcat 7 interreptedExcepption
trying to deploy a war file generating by spring-boot/maven project I get this log error  have someone any idea on it.

stacktrace here :

```<code>  classes started by g688614 in D:\dev\apache-tomcat-7.0.64\bin) 2017-12-04 18:06:18:331 DEBUG c.i.Application.logStarting :

    Running with Spring Boot v1.5.3.RELEASE, Spring v4.3.8.RELEASE 2017-12-04 `18:06:18:331 INFO`
    c.i.Application.logStartupProfileInfo : The following profiles are active: dev dΘc. 04, 2017 6:06:23 PM

    org.apache.coyote.AbstractProtocol pause INFOS: Pausing ProtocolHandler ["http-apr-8080"] dΘc. 04, 2017 6:06:23 PM

    org.apache.coyote.AbstractProtocol pause INFOS: Pausing ProtocolHandler ["ajp-apr-8009"] dΘc. 04, 2017 6:06:23 PM

org.apache.catalina.core.StandardService stopInternal INFOS: ArrΩt du service Catalina dΘc. 04, 2017 6:06:23 PM

    org.apache.catalina.startup.HostConfig deployWARs GRAVE: Error waiting for multi-thread deployment of WAR files to complete

    java.lang.InterruptedException at java.util.concurrent.FutureTask.awaitDone(FutureTask.java:404) at

    java.util.concurrent.FutureTask.get(FutureTask.java:191) at org.apache.catalina.startup.HostConfig.deployWARs(

    HostConfig.java:830) at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:493) at

    org.apache.catalina.startup.HostConfig.check(HostConfig.java:1704) at org.apache.catalina.startup.HostConfig.lifecycleEvent(
    HostConfig.java:333) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117) at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90) at
    org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1373) at

    org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1545) at

    org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1555) at

org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1523) at java.lang.Thread.run(

    Thread.java:745)
</code>```

thank you very much

答:
Use a lower version of tomcat possibly 7.0.28.
The lower version keeps all war related issues resolved.
If the problem still does not solve. Then try to reconfigure tomact.</p>

Title: Tomcat 7 interreptedExcepption

Body:
trying to deploy a war file generating by spring-boot/maven project I get this log error  have someone any idea on it.

stacktrace here :

  classes started by g688614 in D:\dev\apache-tomcat-7.0.64\bin) 2017-12-04 18:06:18:331 DEBUG c.i.Application.logStarting :

    Running with Spring Boot v1.5.3.RELEASE, Spring v4.3.8.RELEASE 2017-12-04 `18:06:18:331 INFO`
    c.i.Application.logStartupProfileInfo : The following profiles are active: dev dΘc. 04, 2017 6:06:23 PM

    org.apache.coyote.AbstractProtocol pause INFOS: Pausing ProtocolHandler ["http-apr-8080"] dΘc. 04, 2017 6:06:23 PM

    org.apache.coyote.AbstractProtocol pause INFOS: Pausing ProtocolHandler ["ajp-apr-8009"] dΘc. 04, 2017 6:06:23 PM

org.apache.catalina.core.StandardService stopInternal INFOS: ArrΩt du service Catalina dΘc. 04, 2017 6:06:23 PM

    org.apache.catalina.startup.HostConfig deployWARs GRAVE: Error waiting for multi-thread deployment of WAR files to complete

    java.lang.InterruptedException at java.util.concurrent.FutureTask.awaitDone(FutureTask.java:404) at

    java.util.concurrent.FutureTask.get(FutureTask.java:191) at org.apache.catalina.startup.HostConfig.deployWARs(

    HostConfig.java:830) at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:493) at

    org.apache.catalina.startup.HostConfig.check(HostConfig.java:1704) at org.apache.catalina.startup.HostConfig.lifecycleEvent(
    HostConfig.java:333) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117) at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90) at
    org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1373) at

    org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1545) at

    org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1555) at

org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1523) at java.lang.Thread.run(

    Thread.java:745)

thank you very much


问:
Map RowDataCollection to DTO using AutoMapper
Is there a way to map a RowDataCollection to DTO using AutoMapper?

Here is a scenario: DataRow to Object

```<code>user.UserId = row["UserId"];
user.UserName = row["UserName"];
</code>```

答: You could do a custom type converter.  And, if you're sure the DTO property names will exactly match the DataRow column names, you could probably do a little reflection and have a single type converter.</p>

Body:
Is there a way to map a RowDataCollection to DTO using AutoMapper?

Here is a scenario: DataRow to Object

user.UserId = row["UserId"];
user.UserName = row["UserName"];


问:
Lock holds thread without acquiring the lock
I have an

```<code>ReentrantLock lock = new ReentrantLock();
</code>```

and 2 methods

```<code>public void m1(){
        lock.lock();
        try {
            System.out.println("m1");
        } finally {
            lock.unlock();
        }
}

public void m2(){
        lock.lock();
        try {
            System.out.println("m2");
        } finally {
            lock.unlock();
        }
}
</code>```

I want only method m2 to held the lock and m1 to just check if the lock is held then wait until is unlocked and execute the code, but I don't want m1 to acquire any lock.

For example:

```<code>T1 -> m1 // no lock acquired
T2 -> m1 // no lock acquired
T3 -> m2 // lock acquired
T4 -> m1 // wait until T3 finish executing m2 then execute m1
</code>```

答:
Just reorder the statements:

```<code>public void m1(){
  lock.lock();
  // No need for finally, no statement to complete abnormally.
  lock.unlock();

  System.out.println("m1");
}
</code>```

Sure, this will acquire the lock; but it immediately releases it again; so the lock isn't held while the statement is printed.

Body:
I have an

ReentrantLock lock = new ReentrantLock();

and 2 methods

public void m1(){
        lock.lock();
        try {
            System.out.println("m1");
        } finally {
            lock.unlock();
        }
}

public void m2(){
        lock.lock();
        try {
            System.out.println("m2");
        } finally {
            lock.unlock();
        }
}

I want only method m2 to held the lock and m1 to just check if the lock is held then wait until is unlocked and execute the code, but I don't want m1 to acquire any lock.

For example:

T1 -> m1 // no lock acquired
T2 -> m1 // no lock acquired
T3 -> m2 // lock acquired
T4 -> m1 // wait until T3 finish executing m2 then execute m1

Body:
Just reorder the statements:

public void m1(){
  lock.lock();
  // No need for finally, no statement to complete abnormally.
  lock.unlock();

  System.out.println("m1");
}

Sure, this will acquire the lock; but it immediately releases it again; so the lock isn't held while the statement is printed.


问:
Updating UI when a model property changes in an ObservableCollection?
I have a view that has a group of images I get from a web service
I receive them in a list of this class:

```<code> public class ImageModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string imageUrl { get; set; }
    }
</code>```

under each image I show an up-vote button, so I added another bool property to the model above:

```<code> public bool UpVoted { get; set; }
</code>```

the ListView that shows these images is bound to an ObservableCollection<ImageModel > , I want to change the voting icon through a converter that convert the value of UpVoted to the corresponding icon, when the user click the voting icon: a command execute this method:

```<code>    private void OnVoting(ImageModel image)
    {
        Images.Single(x => x.id == image.id).UpVoted = !image.UpVoted;
    }
</code>```

the problem is that the UI is not updated, and to make sure that I understood the problem I turned the model to a View model and made the required changes to the UpVoted property (I'm using MVVM light library)

```<code>bool upVoted;
        public bool UpVoted
        {
            get { return upVoted; }
            set
            {
                Set(ref upVoted, value);
            }
        }
</code>```

and it works now,
so I need to bind the UpVoted to the UI, so it's updated whenever it changed

答:
you do not say which sort of container that you are using but not all controls are set to support two way notification by default. so you may have to add a

```<code>Mode=TwoWay
</code>```

to get notifications from the back end that data has changed. Or as the previous answer by Mustafa indicated you may need to verify that your class is implementing the InotifyPropertyChanged event with mvvm light.

Body:
I have a view that has a group of images I get from a web service
I receive them in a list of this class:

 public class ImageModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string imageUrl { get; set; }
    }

under each image I show an up-vote button, so I added another bool property to the model above:

 public bool UpVoted { get; set; }

the ListView that shows these images is bound to an ObservableCollection<ImageModel > , I want to change the voting icon through a converter that convert the value of UpVoted to the corresponding icon, when the user click the voting icon: a command execute this method:

    private void OnVoting(ImageModel image)
    {
        Images.Single(x => x.id == image.id).UpVoted = !image.UpVoted;
    }

the problem is that the UI is not updated, and to make sure that I understood the problem I turned the model to a View model and made the required changes to the UpVoted property (I'm using MVVM light library)

bool upVoted;
        public bool UpVoted
        {
            get { return upVoted; }
            set
            {
                Set(ref upVoted, value);
            }
        }

and it works now,
so I need to bind the UpVoted to the UI, so it's updated whenever it changed

Body:
you do not say which sort of container that you are using but not all controls are set to support two way notification by default. so you may have to add a

Mode=TwoWay

to get notifications from the back end that data has changed. Or as the previous answer by Mustafa indicated you may need to verify that your class is implementing the InotifyPropertyChanged event with mvvm light.


问:
Why doesn't this lifetime bound cause an error?
This code compiles and work, but according to my understanding, it should not compile:

```<code>use std::fmt::Display;

pub fn test<S>(s: S)
where
    S: Display + 'static,
{
    println!("test: {}", s);
}

fn main() {
    let s = String::from("string");

    test(s);
}
</code>```

The lifetime of variable s is in main, but the function test has a bound that S must be 'static. I think the lifetime of variable s must be 'static or larger than 'static. What's wrong with my reasoning?

答:
The bound S: 'a means that any references contained in S must live at least as long as 'a. For S: 'static, this means that references in S must have a 'static lifetime. The String type doesn't hold any references (it owns its data), and therefore the code compiles.

Quoting the book:

Types without any references count as T: 'static. Because 'static means the reference must live as long as the entire program, a type that contains no references meets the criteria of all references living as long as the entire program (since there are no references).

If you call the function with test(&s) instead, compilation will fail:

error[E0597]: `s` does not live long enough
  --> src/main.rs:14:11
   |
14 |     test(&s);
   |           ^ does not live long enough
15 | }
   | - borrowed value only lives until here
   |
   = note: borrowed value must be valid for the static lifetime...
```

Here, S is &'a String for some lifetime 'a, and the lifetime bound requires that 'a must be 'static, which isn't the case.

Body:
This code compiles and work, but according to my understanding, it should not compile:

use std::fmt::Display;

pub fn test<S>(s: S)
where
    S: Display + 'static,
{
    println!("test: {}", s);
}

fn main() {
    let s = String::from("string");

    test(s);
}

The lifetime of variable s is in main, but the function test has a bound that S must be 'static. I think the lifetime of variable s must be 'static or larger than 'static. What's wrong with my reasoning?

Body:
The bound S: 'a means that any references contained in S must live at least as long as 'a. For S: 'static, this means that references in S must have a 'static lifetime. The String type doesn't hold any references (it owns its data), and therefore the code compiles.

Quoting the book:

Types without any references count as T: 'static. Because 'static means the reference must live as long as the entire program, a type that contains no references meets the criteria of all references living as long as the entire program (since there are no references).

If you call the function with test(&s) instead, compilation will fail:

error[E0597]: `s` does not live long enough
  --> src/main.rs:14:11
   |
14 |     test(&s);
   |           ^ does not live long enough
15 | }
   | - borrowed value only lives until here
   |
   = note: borrowed value must be valid for the static lifetime...

Here, S is &'a String for some lifetime 'a, and the lifetime bound requires that 'a must be 'static, which isn't the case.


问:
Why is a bitmask of 0xFFFF used when dwLocalPort from PMIB_TCPROW2 structure?
I found this answer to be useful: Getting PID of peer socket on Windows
.. but also intriguing.

I'm wondering: why are there 16 bits masked in row->dwLocalPort & 0xFFFF out of the 32 DWORD bits in dwLocalPort?

I know that bitmasks are used to add more information into 1 number, but it seems for me that here it is not necessary. Am I overlooking something simple?

答:
As per MSDN "The maximum size of an IP port number is 16 bits, so only the lower 16 bits should be used. The upper 16 bits may contain uninitialized data."

https://msdn.microsoft.com/en-ca/subscriptions/bb485761.aspx


问:
ES6 import nested function - mocha
I am using ES6, and I want to start testing using mocha & chai.

My current test file code is :

```<code>const assert = require('chai').assert;
var app = require('../../../../src/app/login/loginController').default;

describe('login Controller tests', function(){
    it('no idea ', function(){
        let result = app();
        assert.equal(result, 'hello');
    })
})
</code>```

and my loginController.js is :

```<code>class LoginController {

    checkout(){
        return 'hello';
    }
}
export default LoginController
</code>```

I want to import the 'checkout' function into a variable inside my test file, but so far I am able to import only the class.

Will appreciate any help, thanks !

答:
You cannot import methods directly from classes. If you want to import a function without a class as intermediary, then you need to define the function outside the class. Or if you really meant checkout to be an instance method, then you need to call it on an instance.

Here's an example file derived from yours:

```<code>export class LoginController {

    // Satic function
    static moo() {
        return "I'm mooing";
    }

    // Instance method
    checkout() {
        return "hello";
    }
}

// A standalone function.
export function something() {
    return "This is something!";
}
</code>```

And a test file that exercises all functions, adapted from the file you show in your question:

```<code>const assert = require('chai').assert;

// Short of using something to preprocess import statements during
// testing... use destructuring.
const { LoginController, something } = require('./loginController');

describe('login Controller tests', function(){
    it('checkout', function(){
        // It not make sense to call it without ``new``.
        let result = new LoginController();
        // You get an instance method from an instance.
        assert.equal(result.checkout(), 'hello');
    });

    it('moo', function(){
        // You get the static function from the class.
        assert.equal(LoginController.moo(), 'I\'m mooing');
    });

    it('something', function(){
        // Something is exported directly by the module
        assert.equal(something(), 'This is something!');
    });
});
</code>```

Title: ES6 import nested function - mocha

Body:
I am using ES6, and I want to start testing using mocha & chai.

My current test file code is :

const assert = require('chai').assert;
var app = require('../../../../src/app/login/loginController').default;

describe('login Controller tests', function(){
    it('no idea ', function(){
        let result = app();
        assert.equal(result, 'hello');
    })
})

and my loginController.js is :

class LoginController {

    checkout(){
        return 'hello';
    }
}
export default LoginController

I want to import the 'checkout' function into a variable inside my test file, but so far I am able to import only the class.

Will appreciate any help, thanks !

Body:
You cannot import methods directly from classes. If you want to import a function without a class as intermediary, then you need to define the function outside the class. Or if you really meant checkout to be an instance method, then you need to call it on an instance.

Here's an example file derived from yours:

export class LoginController {

    // Satic function
    static moo() {
        return "I'm mooing";
    }

    // Instance method
    checkout() {
        return "hello";
    }
}

// A standalone function.
export function something() {
    return "This is something!";
}

And a test file that exercises all functions, adapted from the file you show in your question:

const assert = require('chai').assert;

// Short of using something to preprocess import statements during
// testing... use destructuring.
const { LoginController, something } = require('./loginController');

describe('login Controller tests', function(){
    it('checkout', function(){
        // It not make sense to call it without ``new``.
        let result = new LoginController();
        // You get an instance method from an instance.
        assert.equal(result.checkout(), 'hello');
    });

    it('moo', function(){
        // You get the static function from the class.
        assert.equal(LoginController.moo(), 'I\'m mooing');
    });

    it('something', function(){
        // Something is exported directly by the module
        assert.equal(something(), 'This is something!');
    });
});


问:
Creating an image summary only for a subset of validation set images using Tensorflow Estimator API
I'm trying to add image summary operations to visualize how well my network manages to reconstruct inputs from the validation set. However, since there are too many images in the validation set I would only like to plot a small subset of them.

I managed to achieve this with manual training loop, but I struggle to achieve the same with the new Tensorflow Estimator/Experiment/Datasets API. Has anyone done something like this?

答:
I figured out a solution that uses Estimator/Experiment API.

First you need to modify your Dataset input to not only provide labels and features, but also some form of an identifier for each sample (in my case it was a filename). Then in the hyperparameters dictionary (params argument) you need to specify which of the validation samples you want to plot. You also will have to pass the model_dir in those parameters. For example:

```<code>params = tf.contrib.training.HParams(
        model_dir=model_dir,
        images_to_plot=["100307_EMOTION.nii.gz", "100307_FACE-SHAPE.nii.gz",
                        "100307_GAMBLING.nii.gz", "100307_RELATIONAL.nii.gz",
                        "100307_SOCIAL.nii.gz"]
    )

learn_runner.run(
        experiment_fn=experiment_fn,
        run_config=run_config,
        schedule="train_and_evaluate",
        hparams=params
    )
</code>```

Having this set up you can create conditional Summary operations in your model_fn and an evaluation hook to include them in your outputs.

```<code>if mode == tf.contrib.learn.ModeKeys.EVAL:
    summaries = []
    for image_to_plot in params.images_to_plot:
        is_to_plot = tf.equal(tf.squeeze(filenames), image_to_plot)

        summary = tf.cond(is_to_plot,
                          lambda: tf.summary.image('predicted', predictions),
                          lambda: tf.summary.histogram("ignore_me", [0]),
                          name="%s_predicted" % image_to_plot)
        summaries.append(summary)

    evaluation_hooks = [tf.train.SummarySaverHook(
        save_steps=1,
        output_dir=os.path.join(params.model_dir, "eval"),
        summary_op=tf.summary.merge(summaries))]
else:
    evaluation_hooks = None
</code>```

Note that the summaries have to be conditional - we are either plotting an image (computationally expensive) or saving a constant (computationally cheap). I opted for using histogram versus scalar in for the dummy summaries to avoid cluttering my tensorboard dashboard.

Finally you need to pass the hook in the return object of your `model_fn'

```<code>return tf.estimator.EstimatorSpec(
    mode=mode,
    predictions=predictions,
    loss=loss,
    train_op=train_op,
    evaluation_hooks=evaluation_hooks
)
</code>```

Please note that this only works when your batch size is 1 when evaluating the model (which should not be a problem).

Body:
I figured out a solution that uses Estimator/Experiment API.

First you need to modify your Dataset input to not only provide labels and features, but also some form of an identifier for each sample (in my case it was a filename). Then in the hyperparameters dictionary (params argument) you need to specify which of the validation samples you want to plot. You also will have to pass the model_dir in those parameters. For example:

params = tf.contrib.training.HParams(
        model_dir=model_dir,
        images_to_plot=["100307_EMOTION.nii.gz", "100307_FACE-SHAPE.nii.gz",
                        "100307_GAMBLING.nii.gz", "100307_RELATIONAL.nii.gz",
                        "100307_SOCIAL.nii.gz"]
    )

learn_runner.run(
        experiment_fn=experiment_fn,
        run_config=run_config,
        schedule="train_and_evaluate",
        hparams=params
    )

Having this set up you can create conditional Summary operations in your model_fn and an evaluation hook to include them in your outputs.

if mode == tf.contrib.learn.ModeKeys.EVAL:
    summaries = []
    for image_to_plot in params.images_to_plot:
        is_to_plot = tf.equal(tf.squeeze(filenames), image_to_plot)

        summary = tf.cond(is_to_plot,
                          lambda: tf.summary.image('predicted', predictions),
                          lambda: tf.summary.histogram("ignore_me", [0]),
                          name="%s_predicted" % image_to_plot)
        summaries.append(summary)

    evaluation_hooks = [tf.train.SummarySaverHook(
        save_steps=1,
        output_dir=os.path.join(params.model_dir, "eval"),
        summary_op=tf.summary.merge(summaries))]
else:
    evaluation_hooks = None

Note that the summaries have to be conditional - we are either plotting an image (computationally expensive) or saving a constant (computationally cheap). I opted for using histogram versus scalar in for the dummy summaries to avoid cluttering my tensorboard dashboard.

Finally you need to pass the hook in the return object of your `model_fn'

return tf.estimator.EstimatorSpec(
    mode=mode,
    predictions=predictions,
    loss=loss,
    train_op=train_op,
    evaluation_hooks=evaluation_hooks
)

Please note that this only works when your batch size is 1 when evaluating the model (which should not be a problem).


问:
nchor Link to Local File? (DEAD LINK not working in FireFox but in IE)
This Java code,

```<code>"<a href='file:///" + curBP.get_build_path() + "'>" + curBP.get_build_path() + "</a>"
</code>```

is outputted to the browser.

On the page, the HTML is:

```<code><a href="file:///\\path\to\shared\file">Shared File</a>
</code>```

However, it does not open the file. I've tried countless other combinations of slashes, but to no avail. In FireFox, it acts like a dead link and does not open the file. In IE, it works.

Any idea as to how to make it work in FireFox? Thanks!

答: When you use backslashes {} , you're calling Windows Explorer. And IE is   integrated with Windows Explorer, FF not    integrated</p>

Body:
This Java code,

"" + curBP.get_build_path() + ""

is outputted to the browser.

On the page, the HTML is:

Shared File

However, it does not open the file. I've tried countless other combinations of slashes, but to no avail. In FireFox, it acts like a dead link and does not open the file. In IE, it works.

Any idea as to how to make it work in FireFox? Thanks!