问:
XHTML to Structured XML with XSLT 1.0
I have an XHTML document from a basic ePub output that I'm trying to convert into a structured XML document. The format of it shouldn't be too crazy in general and looks like the following:

```<code><?xml version="1.0" encoding="utf-8"?>
<html>
<body>
  <h1>Topic 1</h1>
  <p>1.0.1</p>
  <p>1.0.2</p>

  <h2>Subtopic 1.1</h2>
  <p>1.1.1</p>
  <p>1.1.2</p>

  <h2>Subtopic 1.2</h2>
  <p>1.2.1</p>
  <p>1.2.2</p>

  <h1>Topic 2</h1>
  <p>2.0.1</p>
  <p>2.0.2</p>

  <h2>Subtopic 2.1</h2>
  <p>2.1.1</p>
  <p>2.1.2</p>

  <h2>Subtopic 2.2</h2>
  <p>2.2.1</p>
  <p>2.2.2</p>
</body>
</html>
</code>```

Ideally, I'd like to convert this into some structured code, based on the h1, h2, ... tags. The stuff after the first h1, but before the second should be contained inside its own container, and the stuff in the second h1 to the end of the document inside its own. Likewise, the stuff between h2's should also go into a container, thereby nesting it. The output should be something like this:

```<code><Root>
   <Topic>
      <Title>Topic 1</Title>
      <Paragraph>1.0.1</Paragraph>
      <Paragraph>1.0.2</Paragraph>
      <Topic>
         <Title>Subtopic 1.1</Title>
         <Paragraph>1.1.1</Paragraph>
         <Paragraph>1.1.2</Paragraph>
      </Topic>
      <Topic>
         <Title>Subtopic 1.2</Title>
         <Paragraph>1.2.1</Paragraph>
         <Paragraph>1.2.2</Paragraph>
      </Topic>
   </Topic>
   <Topic>
      <Title>Topic 2</Title>
      <Paragraph>2.0.1</Paragraph>
      <Paragraph>2.0.2</Paragraph>
      <Topic>
         <Title>Subtopic 2.1</Title>
         <Paragraph>2.1.1</Paragraph>
         <Paragraph>2.1.2</Paragraph>
      </Topic>
      <Topic>
         <Title>Subtopic 2.2</Title>
         <Paragraph>2.2.1</Paragraph>
         <Paragraph>2.2.2</Paragraph>
      </Topic>
   </Topic>
</Root>
</code>```

Even though the example only consists of p tags, it may also contain div's, and other elements, so don't count on it being just one node. It needs to be generic enough to not care what's between the header tags.

I'm familiar with Muenchian grouping, but this is a bit complex of a situation for me. I've tried using keys like this:

```<code><xsl:key name="kHeaders1" match="*[not(self::h1)]" use="generate-id(preceding-sibling::h1[1])"/>

<xsl:template match="h1">
  <Topic>
    <Title><xsl:apply-templates /></Title>
    <xsl:apply-templates select="key('kHeaders1', generate-id())" />
  </Topic>
</xsl:template>

<xsl:template match="html">
  <Root>
     <xsl:apply-templates select="body/h1" />
  </Root>
</xsl:template>

<xsl:template match="p">
   <Paragraph><xsl:apply-templates /></Paragraph>
</xsl:template>
</code>```

This works well enough for the first level, but then trying to repeat the process, but using h2, seems to break my mind. Since at the h2 level, the key for any node should be the first, h1 or h2 sibling. It almost seems like it could be combined into a single set of keys, where the id is whatever the last h* was that came before it, and where the h* elements are not listed in the grouping (so that they don't recurse). I would imagine something like:

```<code><xsl:key name="kHeaders" match="*[not(self::h1 or self::h2)]" use="generate-id(preceding-sibling::*[self::h1 or self::h2][1])"/>
</code>```

However, that leaves out the h2 elements from the list, which need to be present in the grouping for the previous h1. And if I relax the restrictions on the match to include the h1/h2 elements (and make the h1 templates also match h2), then I get the h2's re-listing the h1's and so on (somewhat expected).

An ideal solution is one that can be extended to work for h3, h4, and so on without a lot of effort. However, it does not need to include script elements for handling the generic h* elements. Simple instructions for how to add an additional layer would be sufficient.

Does anyone have some advice here?

答:
Below stylesheet(most of the essential code copied from this answer) would work when more headers are involved:</p>

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:key name="next-headings" match="h6"
          use="generate-id(preceding-sibling::*[self::h1 or self::h2 or
                                               self::h3 or self::h4 or
                                               self::h5][1])" />

    <xsl:key name="next-headings" match="h5"
          use="generate-id(preceding-sibling::*[self::h1 or self::h2 or
                                               self::h3 or self::h4][1])" />
    <xsl:key name="next-headings" match="h4"
          use="generate-id(preceding-sibling::*[self::h1 or self::h2 or
                                               self::h3][1])" />
    <xsl:key name="next-headings" match="h3"
          use="generate-id(preceding-sibling::*[self::h1 or self::h2][1])" />

    <xsl:key name="next-headings" match="h2"
          use="generate-id(preceding-sibling::h1[1])" />

    <xsl:key name="immediate-nodes"
          match="node()[not(self::h1 | self::h2 | self::h3 | self::h4 |
                           self::h5 | self::h6)]"
          use="generate-id(preceding-sibling::*[self::h1 or self::h2 or
                                               self::h3 or self::h4 or
                                               self::h5 or self::h6][1])" />

    <xsl:template match="/">
        <Root>
            <xsl:apply-templates select="html/body/h1"/>
        </Root>
    </xsl:template>

    <xsl:template match="p">
        <Paragraph>
            <xsl:value-of select="."/>
        </Paragraph>
    </xsl:template>

    <xsl:template match="h1 | h2 | h3 | h4 | h5 | h6">
        <Topic>
            <Title>
                <xsl:value-of select="."/>
            </Title>
            <xsl:apply-templates select="key('immediate-nodes', generate-id())"/>
            <xsl:apply-templates select="key('next-headings', generate-id())"/>
        </Topic>
    </xsl:template>

</xsl:stylesheet>
</code>```

Title: XHTML to Structured XML with XSLT 1.0

Body:
I have an XHTML document from a basic ePub output that I'm trying to convert into a structured XML document. The format of it shouldn't be too crazy in general and looks like the following:

<?xml version="1.0" encoding="utf-8"?>

Topic 1

1.0.1

1.0.2

Subtopic 1.1

1.1.1

1.1.2

Subtopic 1.2

1.2.1

1.2.2

Topic 2

2.0.1

2.0.2

Subtopic 2.1

2.1.1

2.1.2

Subtopic 2.2

2.2.1

2.2.2

Ideally, I'd like to convert this into some structured code, based on the h1, h2, ... tags. The stuff after the first h1, but before the second should be contained inside its own container, and the stuff in the second h1 to the end of the document inside its own. Likewise, the stuff between h2's should also go into a container, thereby nesting it. The output should be something like this:

<Root>
   <Topic>
      <Title>Topic 1</Title>
      <Paragraph>1.0.1</Paragraph>
      <Paragraph>1.0.2</Paragraph>
      <Topic>
         <Title>Subtopic 1.1</Title>
         <Paragraph>1.1.1</Paragraph>
         <Paragraph>1.1.2</Paragraph>
      </Topic>
      <Topic>
         <Title>Subtopic 1.2</Title>
         <Paragraph>1.2.1</Paragraph>
         <Paragraph>1.2.2</Paragraph>
      </Topic>
   </Topic>
   <Topic>
      <Title>Topic 2</Title>
      <Paragraph>2.0.1</Paragraph>
      <Paragraph>2.0.2</Paragraph>
      <Topic>
         <Title>Subtopic 2.1</Title>
         <Paragraph>2.1.1</Paragraph>
         <Paragraph>2.1.2</Paragraph>
      </Topic>
      <Topic>
         <Title>Subtopic 2.2</Title>
         <Paragraph>2.2.1</Paragraph>
         <Paragraph>2.2.2</Paragraph>
      </Topic>
   </Topic>
</Root>

Even though the example only consists of p tags, it may also contain div's, and other elements, so don't count on it being just one node. It needs to be generic enough to not care what's between the header tags.

I'm familiar with Muenchian grouping, but this is a bit complex of a situation for me. I've tried using keys like this:

<xsl:key name="kHeaders1" match="*[not(self::h1)]" use="generate-id(preceding-sibling::h1[1])"/>

<xsl:template match="h1">
  <Topic>
    <Title><xsl:apply-templates /></Title>
    <xsl:apply-templates select="key('kHeaders1', generate-id())" />
  </Topic>
</xsl:template>

<xsl:template match="html">
  <Root>
     <xsl:apply-templates select="body/h1" />
  </Root>
</xsl:template>

<xsl:template match="p">
   <Paragraph><xsl:apply-templates /></Paragraph>
</xsl:template>

This works well enough for the first level, but then trying to repeat the process, but using h2, seems to break my mind. Since at the h2 level, the key for any node should be the first, h1 or h2 sibling. It almost seems like it could be combined into a single set of keys, where the id is whatever the last h* was that came before it, and where the h* elements are not listed in the grouping (so that they don't recurse). I would imagine something like:

<xsl:key name="kHeaders" match="*[not(self::h1 or self::h2)]" use="generate-id(preceding-sibling::*[self::h1 or self::h2][1])"/>

However, that leaves out the h2 elements from the list, which need to be present in the grouping for the previous h1. And if I relax the restrictions on the match to include the h1/h2 elements (and make the h1 templates also match h2), then I get the h2's re-listing the h1's and so on (somewhat expected).

An ideal solution is one that can be extended to work for h3, h4, and so on without a lot of effort. However, it does not need to include script elements for handling the generic h* elements. Simple instructions for how to add an additional layer would be sufficient.

Does anyone have some advice here?

Body:
Below stylesheet(most of the essential code copied from this answer) would work when more headers are involved:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:key name="next-headings" match="h6"
          use="generate-id(preceding-sibling::*[self::h1 or self::h2 or
                                               self::h3 or self::h4 or
                                               self::h5][1])" />

    <xsl:key name="next-headings" match="h5"
          use="generate-id(preceding-sibling::*[self::h1 or self::h2 or
                                               self::h3 or self::h4][1])" />
    <xsl:key name="next-headings" match="h4"
          use="generate-id(preceding-sibling::*[self::h1 or self::h2 or
                                               self::h3][1])" />
    <xsl:key name="next-headings" match="h3"
          use="generate-id(preceding-sibling::*[self::h1 or self::h2][1])" />

    <xsl:key name="next-headings" match="h2"
          use="generate-id(preceding-sibling::h1[1])" />

    <xsl:key name="immediate-nodes"
          match="node()[not(self::h1 | self::h2 | self::h3 | self::h4 |
                           self::h5 | self::h6)]"
          use="generate-id(preceding-sibling::*[self::h1 or self::h2 or
                                               self::h3 or self::h4 or
                                               self::h5 or self::h6][1])" />

    <xsl:template match="/">
        <Root>
            <xsl:apply-templates select="html/body/h1"/>
        </Root>
    </xsl:template>

    <xsl:template match="p">
        <Paragraph>
            <xsl:value-of select="."/>
        </Paragraph>
    </xsl:template>

    <xsl:template match="h1 | h2 | h3 | h4 | h5 | h6">
        <Topic>
            <Title>
                <xsl:value-of select="."/>
            </Title>
            <xsl:apply-templates select="key('immediate-nodes', generate-id())"/>
            <xsl:apply-templates select="key('next-headings', generate-id())"/>
        </Topic>
    </xsl:template>

</xsl:stylesheet>


来源: stackexchange

问:
Dafny recursive assertion violation
I am new to dafny and am trying to get this simple piece of code to work. I want to count the occurrences of a char in a string. I am receiving an assertion violation on line 4. I know my function is finding the right amount of characters, but clearly there are some holes in this assertion. I'm trying to get the basics down before I start using pre and post conditions and what not, and this should be possible without them. The function simply checks the last character in the string and returns a 1 or 0, along with calling the function again which cuts off the tail of the string until it is empty.

```<code>method Main() {
  var s:string := "hello world";
  print tally(s, 'l');
  assert tally(s,'l') == 3;
}
function method tally(s: string, letter: char): nat
{
  if |s| == 0 then 0
  else if s[|s|-1] == letter then 1+tally(s[..|s|-1], letter)
  else 0 + tally(s[..|s|-1], letter)
}
</code>```

http://rise4fun.com/Dafny/2lvt
Here is the link to my code.

答:
It would be natural to think that the Dafny static verifier can
evaluate any code, like the expression in your assert statement. The
verifier does try to evaluate expressions like these where the
arguments are given as constants (like your "hello world", 'l',
and 3). However, the static verifier wants to avoid recursing
forever (or even recursing for too long), so it doesn't always fully
go through these expressions. In your case, there are also limits to
what the verifier is able to do with the sequence operations. So, in
short, although the verifier tries to be helpful, it does not always
get to the bottom of the recursions.

There are two ways you can work around these limits to get the
verifier to accept your assertion.

The most reliable way to debug the situation is to start with smaller
inputs and build up to the longer inputs you're using. This is quite
tedious, however, and it makes you appreciate when Dafny is able to do
these things automatically.  The following (which verifies)
illustrates what you would do:

```<code>var s := "hello world";
assert tally("he",'l') == 0;
assert tally("hel",'l') == 1;
assert "hell"[..3] == "hel";
assert tally("hell",'l') == 2;
assert "hello"[..4] == "hell";
assert tally("hello",'l') == 2;
assert "hello "[..5] == "hello";
assert tally("hello ",'l') == 2;
assert "hello w"[..6] == "hello ";
assert tally("hello w",'l') == 2;
assert "hello wo"[..7] == "hello w";
assert tally("hello wo",'l') == 2;
assert "hello wor"[..8] == "hello wo";
assert tally("hello wor",'l') == 2;
assert "hello worl"[..9] == "hello wor";
assert tally("hello worl",'l') == 3;
assert s[..10] == "hello worl";
assert tally(s,'l') == 3;
</code>```

In fact, the thing that the Dafny verifier does not expand (too many
times) for you are the "take" operations (that is, the expressions of
the form s[..E]).  The following intermediate assertions will also
verify themselves and will help to verify the final assertion.  These
intermediate assertions show what the verifier doesn't think to do
automatically for you.

```<code>var s := "hello world";
assert "he"[..1] == "h";
assert "hel"[..2] == "he";
assert "hell"[..3] == "hel";
assert "hello"[..4] == "hell";
assert "hello "[..5] == "hello";
assert "hello w"[..6] == "hello ";
assert "hello wo"[..7] == "hello w";
assert "hello wor"[..8] == "hello wo";
assert "hello worl"[..9] == "hello wor";
assert s[..10] == "hello worl";
assert tally(s,'l') == 3;
</code>```

You might wonder, "how in the world would I come up with this?".  The
most systematic way would be to start like in my first example above.
Then, you could try pruning the many assertions there to see what it
is the verifier needs.

(I'm now thinking that perhaps the Dafny verifier could be enhanced to
do these operations, too. It may cause performance problems
elsewhere. I shall take a look.)

The other way to work around the verifier's limits is to define
function tally in a different way, in particular avoiding the "take"
operations, which the verifier does not want to expand a lot.  It is
not clear what to change to make the verifier happy in these
situations, or if that's even possible at all, so this workaround may
not be the best.  Nevertheless, I tried the following definition of
tally and it makes your assertion go through:

```<code>function method tally'(s: string, letter: char): nat
{
  tally_from(s, letter, 0)
}
function method tally_from(s: string, letter: char, start: nat): nat
  requires start <= |s|
  decreases |s| - start
{
  if start == |s| then 0
  else (if s[start] == letter then 1 else 0) + tally_from(s, letter, start+1)
}
</code>```

Note that these definitions do not use any "take" operations.  Here,
the verifier is happy to expand all the recursive calls until the
final answer is found.

Rustan

ContentLicense: CC BY-SA 3.0

Title: Dafny recursive assertion violation

Body:
I am new to dafny and am trying to get this simple piece of code to work. I want to count the occurrences of a char in a string. I am receiving an assertion violation on line 4. I know my function is finding the right amount of characters, but clearly there are some holes in this assertion. I'm trying to get the basics down before I start using pre and post conditions and what not, and this should be possible without them. The function simply checks the last character in the string and returns a 1 or 0, along with calling the function again which cuts off the tail of the string until it is empty.

method Main() {
  var s:string := "hello world";
  print tally(s, 'l');
  assert tally(s,'l') == 3;
}
function method tally(s: string, letter: char): nat
{
  if |s| == 0 then 0
  else if s[|s|-1] == letter then 1+tally(s[..|s|-1], letter)
  else 0 + tally(s[..|s|-1], letter)
}

http://rise4fun.com/Dafny/2lvt
Here is the link to my code.

Body:
It would be natural to think that the Dafny static verifier can
evaluate any code, like the expression in your assert statement. The
verifier does try to evaluate expressions like these where the
arguments are given as constants (like your "hello world", 'l',
and 3). However, the static verifier wants to avoid recursing
forever (or even recursing for too long), so it doesn't always fully
go through these expressions. In your case, there are also limits to
what the verifier is able to do with the sequence operations. So, in
short, although the verifier tries to be helpful, it does not always
get to the bottom of the recursions.

There are two ways you can work around these limits to get the
verifier to accept your assertion.

The most reliable way to debug the situation is to start with smaller
inputs and build up to the longer inputs you're using. This is quite
tedious, however, and it makes you appreciate when Dafny is able to do
these things automatically.  The following (which verifies)
illustrates what you would do:

var s := "hello world";
assert tally("he",'l') == 0;
assert tally("hel",'l') == 1;
assert "hell"[..3] == "hel";
assert tally("hell",'l') == 2;
assert "hello"[..4] == "hell";
assert tally("hello",'l') == 2;
assert "hello "[..5] == "hello";
assert tally("hello ",'l') == 2;
assert "hello w"[..6] == "hello ";
assert tally("hello w",'l') == 2;
assert "hello wo"[..7] == "hello w";
assert tally("hello wo",'l') == 2;
assert "hello wor"[..8] == "hello wo";
assert tally("hello wor",'l') == 2;
assert "hello worl"[..9] == "hello wor";
assert tally("hello worl",'l') == 3;
assert s[..10] == "hello worl";
assert tally(s,'l') == 3;

In fact, the thing that the Dafny verifier does not expand (too many
times) for you are the "take" operations (that is, the expressions of
the form s[..E]).  The following intermediate assertions will also
verify themselves and will help to verify the final assertion.  These
intermediate assertions show what the verifier doesn't think to do
automatically for you.

var s := "hello world";
assert "he"[..1] == "h";
assert "hel"[..2] == "he";
assert "hell"[..3] == "hel";
assert "hello"[..4] == "hell";
assert "hello "[..5] == "hello";
assert "hello w"[..6] == "hello ";
assert "hello wo"[..7] == "hello w";
assert "hello wor"[..8] == "hello wo";
assert "hello worl"[..9] == "hello wor";
assert s[..10] == "hello worl";
assert tally(s,'l') == 3;

You might wonder, "how in the world would I come up with this?".  The
most systematic way would be to start like in my first example above.
Then, you could try pruning the many assertions there to see what it
is the verifier needs.

(I'm now thinking that perhaps the Dafny verifier could be enhanced to
do these operations, too. It may cause performance problems
elsewhere. I shall take a look.)

The other way to work around the verifier's limits is to define
function tally in a different way, in particular avoiding the "take"
operations, which the verifier does not want to expand a lot.  It is
not clear what to change to make the verifier happy in these
situations, or if that's even possible at all, so this workaround may
not be the best.  Nevertheless, I tried the following definition of
tally and it makes your assertion go through:

function method tally'(s: string, letter: char): nat
{
  tally_from(s, letter, 0)
}
function method tally_from(s: string, letter: char, start: nat): nat
  requires start <= |s|
  decreases |s| - start
{
  if start == |s| then 0
  else (if s[start] == letter then 1 else 0) + tally_from(s, letter, start+1)
}

Note that these definitions do not use any "take" operations.  Here,
the verifier is happy to expand all the recursive calls until the
final answer is found.

Rustan


问:
Meaning of different indicators when using 'ls -F'
I'm currently studying Bash shell and have encountered command ls -F. I know it ls function is to append indicators to items lists, so to distinguish between different file types. I know that / is appended to directory and * is appended to executable files. But I have checked the manual page on ls command but couldn't find any information on indicator =>@|.

Could someone tell me what they represent? And it would be even better if can inform me where to find this kind of information when in need.

答:
Try info ls, under "What information is listed":

```<code>‘-F’
‘--classify’
‘--indicator-style=classify’
Append a character to each file name indicating the file type.
     Also, for regular files that are executable, append ‘*’.  The file
     type indicators are ‘/’ for directories, ‘@’ for symbolic links,
     ‘|’ for FIFOs, ‘=’ for sockets, ‘>’ for doors, and nothing for
     regular files.  Do not follow symbolic links listed on the command
     line unless the ‘--dereference-command-line’ (‘-H’),
     ‘--dereference’ (‘-L’), or
     ‘--dereference-command-line-symlink-to-dir’ options are specified.
</code>```

Body:
Try info ls, under "What information is listed":

‘-F’
‘--classify’
‘--indicator-style=classify’
Append a character to each file name indicating the file type.
     Also, for regular files that are executable, append ‘*’.  The file
     type indicators are ‘/’ for directories, ‘@’ for symbolic links,
     ‘|’ for FIFOs, ‘=’ for sockets, ‘>’ for doors, and nothing for
     regular files.  Do not follow symbolic links listed on the command
     line unless the ‘--dereference-command-line’ (‘-H’),
     ‘--dereference’ (‘-L’), or
     ‘--dereference-command-line-symlink-to-dir’ options are specified.


问:
"Undefined variable: Environment" when editing SConscript file in Eclipse Neon
I have an SCons project (an implementation of the Generic Mapping Tools tutorial at http://gmt.soest.hawaii.edu/doc/latest/GMT_Tutorial.html using SCons rather than shell scripts), and I am using Eclipse Neon to edit the Sconstruct file.

The Sconstruct file starts in quite a standard way (the rest of the file is immaterial to this question).

```<code>import os
import collections

env = Environment(ENV = os.environ)

bld = Builder(action = 'ps2pdf $SOURCE $TARGET', \
              suffix = '.pdf', \
              src_suffix = '.ps')
</code>```

What is annoying me is that while the build works perfectly using scons, Eclipse keeps marking the Environment and Builder constructions as "Undefined variables".

I installed the SConsolidator plugin, but it makes no difference.

I find the marking of an error that is not an error incredibly annoying.

While I could do something like tell Eclipse to ignore the error, I would prefer something more intelligent, such as adding Scons to the library path. I have tried adding C:\Python27\Lib\site-packages\scons-2.5.1\Scons and C:\Python27\Lib\site-packages\scons-2.5.1\Scons\Scripts to the Python Interpreter Paths (Window → Preferences → PyDev → Interpreters → Python Interpreters → Paths), and using an import directive like from SConscript.SCons import * but it doesn't make a difference.

答:
Try library path:

```<code>C:\Python27\Lib\site-packages\scons-2.5.1\
</code>```

Then

```<code>from SCons.Script import *
</code>```

Body:
I have an SCons project (an implementation of the Generic Mapping Tools tutorial at http://gmt.soest.hawaii.edu/doc/latest/GMT_Tutorial.html using SCons rather than shell scripts), and I am using Eclipse Neon to edit the Sconstruct file.

The Sconstruct file starts in quite a standard way (the rest of the file is immaterial to this question).

import os
import collections

env = Environment(ENV = os.environ)

bld = Builder(action = 'ps2pdf $SOURCE $TARGET', \
              suffix = '.pdf', \
              src_suffix = '.ps')

What is annoying me is that while the build works perfectly using scons, Eclipse keeps marking the Environment and Builder constructions as "Undefined variables".

I installed the SConsolidator plugin, but it makes no difference.

I find the marking of an error that is not an error incredibly annoying.

While I could do something like tell Eclipse to ignore the error, I would prefer something more intelligent, such as adding Scons to the library path. I have tried adding C:\Python27\Lib\site-packages\scons-2.5.1\Scons and C:\Python27\Lib\site-packages\scons-2.5.1\Scons\Scripts to the Python Interpreter Paths (Window → Preferences → PyDev → Interpreters → Python Interpreters → Paths), and using an import directive like from SConscript.SCons import * but it doesn't make a difference.

Body:
Try library path:

C:\Python27\Lib\site-packages\scons-2.5.1\

Then

from SCons.Script import *


问:
How to initialize an array in Kotlin with values?
In Java an array can be initialized such as:

```<code>int numbers[] = new int[] {10, 20, 30, 40, 50}
</code>```

How does Kotlin's array initialization look like?

答:
Old question, but if you'd like to use a range:

```<code>var numbers: IntArray = IntRange(10, 50).step(10).toList().toIntArray()
</code>```

Yields nearly the same result as:

```<code>var numbers = Array(5, { i -> i*10 + 10 })
</code>```

result: 10, 20, 30, 40, 50

I think the first option is a little more readable. Both work.

Body:
In Java an array can be initialized such as:

int numbers[] = new int[] {10, 20, 30, 40, 50}

How does Kotlin's array initialization look like?

Body:
Old question, but if you'd like to use a range:

var numbers: IntArray = IntRange(10, 50).step(10).toList().toIntArray()

Yields nearly the same result as:

var numbers = Array(5, { i -> i*10 + 10 })

result: 10, 20, 30, 40, 50

I think the first option is a little more readable. Both work.


问:
How does Rails find the correct database adapter through the database.yml?
The database.yml file has a adapter: postgresql, how does this lead the rails server to connect to the postgres program? If I'm running the server locally does Rails look through my PATH or something to find the location of where my postgres is installed?

答:
databases are client-server software. So your rails app connects to the database server via hostname/IP address, port number and db credentials (username/password) which can exist anywhere on the network.

If you are developing a rails application on your localhost and have the database binaries installed on the same machine you are developing. Then, in order to connect to that db server, you must have a database daemon running on your localhost listening to a port (deafault port is 5432 for postgresql). You can test status of your postgres daemon using netstat -an | grep 5432

you can change the port number on your app's config/database.yml if you are using a different one (if you do not specify port number and using postgresql adaptor, it assumes the default port number 5432)

```<code>development:
  adapter: postgresql
  encoding: utf8
  database: app_dev
  username: dev_user
  password: dev_pass
  host: localhost
  port: 5432
</code>```

Body:
databases are client-server software. So your rails app connects to the database server via hostname/IP address, port number and db credentials (username/password) which can exist anywhere on the network.

If you are developing a rails application on your localhost and have the database binaries installed on the same machine you are developing. Then, in order to connect to that db server, you must have a database daemon running on your localhost listening to a port (deafault port is 5432 for postgresql). You can test status of your postgres daemon using netstat -an | grep 5432

you can change the port number on your app's config/database.yml if you are using a different one (if you do not specify port number and using postgresql adaptor, it assumes the default port number 5432)

development:
  adapter: postgresql
  encoding: utf8
  database: app_dev
  username: dev_user
  password: dev_pass
  host: localhost
  port: 5432


问:
Node / Javascript import different modules based on target platform?
I would like to know what methods are available to specify which modules should my app import based on a target platform. I would like to import different implementations  for the same interface in typescript for a browser and for a nodejs.

We have something like

```<code>#ifdef windows
#include "windowsimplementation.h"
#endif
</code>```

In c++

How could i achieve something similar using typescript node and browserify?

答:
which modules should my app import based on a target platform

Use the browser property in package.json.

More

Docs https://github.com/defunctzombie/package-browser-field-spec

Recommend creating a node implementation as default and point types to the definitions generated from that. More on types : https://egghead.io/lessons/typescript-create-high-quality-npm-packages-using-typescript

Body:
I would like to know what methods are available to specify which modules should my app import based on a target platform. I would like to import different implementations  for the same interface in typescript for a browser and for a nodejs.

We have something like

#ifdef windows
#include "windowsimplementation.h"
#endif

In c++

How could i achieve something similar using typescript node and browserify?


问:
How do you print received cookie info to stdout with curl?
How do you print received cookie info to stdout with curl?

According to the man pages if you use '-' as the file name for the -c --cookie-jar option it should print the cookie to stdout. The problem is I get an error:

```<code>curl: option -: is unknown
</code>```

an example of the command I am running:

```<code>curl -c --cookie-jar - 'http://google.com'
</code>```

答:
You need to use two options to get only the cookie text on stdout:

--cookie-jar <file name> from the man page:

If you set the file name to a single dash, '-', the cookies will be written to stdout.

--output <file> from the man page:

Write output to  instead of stdout.

Set it to /dev/null to throw it away.

--silent is also helpful.

Putting it all together:

```<code>curl --silent --output /dev/null --cookie-jar - 'http://www.google.com/'
</code>```

Output:

```<code># Netscape HTTP Cookie File
# https://curl.haxx.se/docs/http-cookies.html
# This file was generated by libcurl! Edit at your own risk.

#HttpOnly_.google.com   TRUE    /   FALSE   1512524163  NID 105=DownH33BKZnCsWJeGvsIC5cKRi7CPT3K3QjfUB-4js5xGw6P_6svMqU1yKlKOEu4XwL_TdddZlcMITefFGOtCCyzJNhO_7E9UMNpbQHja40IAerYP5Bwj-FhY1m35mZdvkVSmrg1pZPvH96IkVVVVVVVV
</code>```

My use case: Test that your website uses the HttpOnly cookie setting, per the OWASP recommendation:

```<code>curl --silent --output /dev/null --cookie-jar - 'http://www.google.com/' | grep HttpOnly
</code>```

Body:
How do you print received cookie info to stdout with curl?

According to the man pages if you use '-' as the file name for the -c --cookie-jar option it should print the cookie to stdout. The problem is I get an error:

curl: option -: is unknown

an example of the command I am running:

curl -c --cookie-jar - 'http://google.com'

Body:
You need to use two options to get only the cookie text on stdout:

--cookie-jar <file name> from the man page:

If you set the file name to a single dash, '-', the cookies will be written to stdout.

--output <file> from the man page:

Write output to  instead of stdout.

Set it to /dev/null to throw it away.

--silent is also helpful.

Putting it all together:

curl --silent --output /dev/null --cookie-jar - 'http://www.google.com/'

Output:

# Netscape HTTP Cookie File
# https://curl.haxx.se/docs/http-cookies.html
# This file was generated by libcurl! Edit at your own risk.

#HttpOnly_.google.com   TRUE    /   FALSE   1512524163  NID 105=DownH33BKZnCsWJeGvsIC5cKRi7CPT3K3QjfUB-4js5xGw6P_6svMqU1yKlKOEu4XwL_TdddZlcMITefFGOtCCyzJNhO_7E9UMNpbQHja40IAerYP5Bwj-FhY1m35mZdvkVSmrg1pZPvH96IkVVVVVVVV

My use case: Test that your website uses the HttpOnly cookie setting, per the OWASP recommendation:

curl --silent --output /dev/null --cookie-jar - 'http://www.google.com/' | grep HttpOnly

ContentLicense: CC BY-SA 4.0


问:
Processing some directives leaving others
I use to go through C code having lot of #ifdef, #if and #endif directive which keep some portion active and some portion inactive depending on some variables are defined or not. I searched for something that can process them to generate final C code. But the preprocessing also does the same for #include and #define. But I want to keep them.

So, is there any thing to preprocess these files or project with some filtering?

答: what you want might be actually a bad idea, as there might be definitions coming from included files, describing your architecture, for example... But any modern IDE can visualize the #if preprocessor directives.</p>

ContentLicense: CC BY-SA 2.5


问:
Regular expression for hgsv notation in java
HGSV nomenclature has a pattern:

xxxxx.yyyy:charactersnumbercharacters

I would like to make a regex in java and fetch the all the tokens from above eg:
it should have 5 tokens :
{ 'xxxxx', 'yyyy', 'characters', 'number' , 'characters'}

I have used simple split methodology to fetch the tokens, but I don't find its an optimal solution:

my current code is :

```<code>String hgsv = "BRAF.p:V600E";
String[] tokens = hgsv.split(".");
this.symbol = tokens[0];
String type = tokens[1].split(":")[0];
</code>```

I would like to use Pattern and Matcher in Java. No idea, how to make regex for the above token.

Any clue how to do that?
(even to separate characters, numbers, characters I will be using regex). So why not to use REGEX for entire token.

I found link but this is in Python, I need similar in Java.

答:
I think what you're probably looking for is to use capture groups, like this:

```<code>String  s = "BRAF.p:V600E";
Pattern p = Pattern.compile("(\\w+)\\.(\\w+):([a-zA-Z]+)(\\d+)([a-zA-Z]+)");
Matcher m = p.matcher(s);
if (m.matches()) {
    String[] parts = {m.group(1),
                      m.group(2),
                      m.group(3),
                      m.group(4),
                      m.group(5)};
    // Prints "[BRAF, p, V, 600, E]"
    System.out.println(Arrays.toString(parts));
} else {
    // The input String is invalid.
}
</code>```

That's really just a lot like a split, but it's more stable because you're using the pattern to validate the String beforehand.

Note that I have no idea if that is the exact right pattern that you should be using. I don't know the exact details of the HGSV notation you're talking about and your description is actually pretty vague. (What are e.g. xxxxx and yyyy? What are "characters"?) If you link me to some sort of specification or detailed description of this notation I can try to write a regex that's more definitely correct.

Anyhow, my example shows the basic idea. You might also see http://www.regular-expressions.info/brackets.html for more information.

Body:
HGSV nomenclature has a pattern:

xxxxx.yyyy:charactersnumbercharacters

I would like to make a regex in java and fetch the all the tokens from above eg:
it should have 5 tokens :
{ 'xxxxx', 'yyyy', 'characters', 'number' , 'characters'}

I have used simple split methodology to fetch the tokens, but I don't find its an optimal solution:

my current code is :

String hgsv = "BRAF.p:V600E";
String[] tokens = hgsv.split(".");
this.symbol = tokens[0];
String type = tokens[1].split(":")[0];

I would like to use Pattern and Matcher in Java. No idea, how to make regex for the above token.

Any clue how to do that?
(even to separate characters, numbers, characters I will be using regex). So why not to use REGEX for entire token.

I found link but this is in Python, I need similar in Java.

Body:
I think what you're probably looking for is to use capture groups, like this:

String  s = "BRAF.p:V600E";
Pattern p = Pattern.compile("(\\w+)\\.(\\w+):([a-zA-Z]+)(\\d+)([a-zA-Z]+)");
Matcher m = p.matcher(s);
if (m.matches()) {
    String[] parts = {m.group(1),
                      m.group(2),
                      m.group(3),
                      m.group(4),
                      m.group(5)};
    // Prints "[BRAF, p, V, 600, E]"
    System.out.println(Arrays.toString(parts));
} else {
    // The input String is invalid.
}

That's really just a lot like a split, but it's more stable because you're using the pattern to validate the String beforehand.

Note that I have no idea if that is the exact right pattern that you should be using. I don't know the exact details of the HGSV notation you're talking about and your description is actually pretty vague. (What are e.g. xxxxx and yyyy? What are "characters"?) If you link me to some sort of specification or detailed description of this notation I can try to write a regex that's more definitely correct.

Anyhow, my example shows the basic idea. You might also see http://www.regular-expressions.info/brackets.html for more information.


问:
How to get maxPwdAge for by Organization Unit or Group wise in active directory
I want to get maxPwdAge value for specific Organization Unit or Group wise.Anybody help me how to do it.

I am able to get domain level maxPwdAge like below, but how can i get Group or OU level maxPwdAge.
Anybody please help me.

```<code> long maxPwdAge=0;
string domain="LDAP://10.10.1.100/OU=Dev,DC=test,DC=com";
string adsiUserName="test";
string adsiPassword="test";
DirectoryEntry entry = new DirectoryEntry(domain, adsiUserName, adsiPassword, AuthenticationTypes.Secure);
DirectorySearcher mySearcher = new DirectorySearcher(entry);
string filter = "(maxPwdAge=*)"; //"maxPwdAge=*";
mySearcher.Filter = filter;
SearchResult results = mySearcher.FindOne();
if (results != null)
{
Int64 pwdAge = (Int64)results.Properties["maxPwdAge"][0];
maxPwdAge = pwdAge / -864000000000;
}
</code>```

答: Your problem is most likely that you're filtering by password max age and not adding it to the properties.</p>

Body:
I want to get maxPwdAge value for specific Organization Unit or Group wise.Anybody help me how to do it.

I am able to get domain level maxPwdAge like below, but how can i get Group or OU level maxPwdAge.
Anybody please help me.

 long maxPwdAge=0;
string domain="LDAP://10.10.1.100/OU=Dev,DC=test,DC=com";
string adsiUserName="test";
string adsiPassword="test";
DirectoryEntry entry = new DirectoryEntry(domain, adsiUserName, adsiPassword, AuthenticationTypes.Secure);
DirectorySearcher mySearcher = new DirectorySearcher(entry);
string filter = "(maxPwdAge=*)"; //"maxPwdAge=*";
mySearcher.Filter = filter;
SearchResult results = mySearcher.FindOne();
if (results != null)
{
Int64 pwdAge = (Int64)results.Properties["maxPwdAge"][0];
maxPwdAge = pwdAge / -864000000000;
}


问:
ASP.NET Core Permissions
I am lost in all options that is possible for managing what a user can do and what a user can not do.
I started with Roles: [Authorize(Roles = Constants.Roles.ModeratorAndUp)]. Where ModeratorAndUp is string "Moderators, Administrators".

But I need more flexible approach. For the past 3 hours I am reading about Claims and permissinos. I also found this interesting blog post.

I am using Angular and ASP.NET Core together with Universal template. For authentication I am using OpenIddict. I was following a book.

I want to use JWT token for authorisation and authentication. I don't know how permission should be handled in .NET Core, but I have 100 different Roles and it is complete mess. And also when I create new user, I need to manually add it arround 20 roles. It would be nice If I could create Groups which has Roles/Permissions and then add User to this group. But don't know how this design will play with OpenIdDict and JWT token authorisation.

Can someone point me in the right direction, and then I will research on my own.

I am not sure should I build some system that will automatically update user roles when I change Group Permissions/Roles, should I go with Claims ... I would like to use [Authorize] attribute, because it really simplify things.

What/how/which is the best practice to do JWT Token authentication/authorisation in ASP.NET Core.

答:
Think of claims as being something a bit more flexible than roles. That said, if you have complex business rules that don't necessarily map simply to groups the user belongs to, you can encapsulate your permissions into Privileges (classes whose responsibility is to determine whether a given user has a certain privilege over a given resource. See more here: http://ardalis.com/favor-privileges-over-role-checks

This tends to reduce a lot of conditional complexity in your UI layer, in my experience.

Title: ASP.NET Core Permissions


问:
Mapping array of objects to array of arrays with headers using ES6
I want to map an array of objects, which I got from a json response of my backend, to an array of arrays, with the first row being an array of headers (titles). I'll use this array to make it downloadable in a csv file.

Also, I want to keep away a couple of headers / columns that are not really interesting for the end user to have in their csv file.

My code is working fine, but I have the idea that it can be done with more concise code. I'm fine with using ES6 / ES2015, but not really experienced with spread syntax and other ES6 goodies myself, so any suggestions for a better, more modern (functional / reactive?) approach are greatly appreciated.

const originalData = [
  {name: 'Gizmo', species: 'cat', age: '9', raw: 'G9e76rd', updated_at: '1318874398806', skill: 'sleeping'},
  {name: 'Benny', species: 'dog', age: '3', raw: '98HDo2h', updated_at: '1318874392417', skill: 'chasing tail'},
  {name: 'Oscar', species: 'cat', age: '2', raw: '9da8Ro1', updated_at: '1318874390283', skill: 'meowing'}
]

let headers = []
const firstRow = originalData[0]
for (var key in firstRow) {
  if (firstRow.hasOwnProperty(key)) {
    if (!['raw','updated_at'].includes(key)) {
      headers.push(key)
    }
  }
}

const d = originalData.map(function(_, i) {
  return headers.map(function(header) {
    return originalData[i][header]
  }.bind(this))
}.bind(this))

const result = [headers].concat(d)

console.log(result)```

答:
A single line of code in an unbroken chain using a filter and reduce.

var unborken = chain => chain.filter((_, i, xx) =>
delete xx[i].updated_at && delete xx[i].raw).reduce((aac, _, i, aa) =>
(i === 0 ? aac.push(Object.keys(aa[i])) && aac.push(Object.values(aa[i])) :
aac.push(Object.values(aa[i])), aac), []);

const originalData = [{
    name: 'Gizmo',
    species: 'cat',
    age: '9',
    raw: 'G9e76rd',
    updated_at: '1318874398806',
    skill: 'sleeping'
  },
  {
    name: 'Benny',
    species: 'dog',
    age: '3',
    raw: '98HDo2h',
    updated_at: '1318874392417',
    skill: 'chasing tail'
  },
  {
    name: 'Oscar',
    species: 'cat',
    age: '2',
    raw: '9da8Ro1',
    updated_at: '1318874390283',
    skill: 'meowing'
  }
];

console.log(unborken(originalData));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
A single line of code in an unbroken chain using a filter and reduce.

var unborken = chain => chain.filter((_, i, xx) =>
delete xx[i].updated_at && delete xx[i].raw).reduce((aac, _, i, aa) =>
(i === 0 ? aac.push(Object.keys(aa[i])) && aac.push(Object.values(aa[i])) :
aac.push(Object.values(aa[i])), aac), []);

const originalData = [{
    name: 'Gizmo',
    species: 'cat',
    age: '9',
    raw: 'G9e76rd',
    updated_at: '1318874398806',
    skill: 'sleeping'
  },
  {
    name: 'Benny',
    species: 'dog',
    age: '3',
    raw: '98HDo2h',
    updated_at: '1318874392417',
    skill: 'chasing tail'
  },
  {
    name: 'Oscar',
    species: 'cat',
    age: '2',
    raw: '9da8Ro1',
    updated_at: '1318874390283',
    skill: 'meowing'
  }
];

console.log(unborken(originalData));

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Bold conditional formatting script for Google Spreadsheets
What I want to do is essentially what this user wanted to do here:

I need a script that formats the cells in column A bold, but only the cells that contain the word 'Hello'.

However I have no knowledge of Google Apps scripts at all, and I need an answer put in much simpler terms than what I could find there or anywhere else. Any help is appreciated; thank you!

答:
In the now not so new 'New' Sheets this can be achieved without a script:

Clear formatting, select ColumnA and Format, Conditional formatting..., Format cells if... Text contains and:

```<code>hello
</code>```

Then for Formatting style click the B and Done.

This way is not case sensitive and will embolden contents such as OTHELLO.

Body:
In the now not so new 'New' Sheets this can be achieved without a script:

Clear formatting, select ColumnA and Format, Conditional formatting..., Format cells if... Text contains and:

hello

Then for Formatting style click the B and Done.

This way is not case sensitive and will embolden contents such as OTHELLO.


问:
New Issue, defining Fields/RecordsWAS Why can't I use DAO in VBA Program written in Excel 2013
Please refer to latest comment by me as I have one more follow up question about column names/reassigning header row.  Thanks! KDL!

OK, I am able to Open the "database" so I can set up queries of recordsets using DAO, and I have figured out how to define a named range so I have a variable that can act as the "Field Name".  I am having an issue with VBA code to insert that Named range into the SELECT SQL statement.  This is the relevant section of code that I am still having a problem with

BEGIN CODE
'**********************************
Dim db as DAO.Database
Dim rst as DAO.Recordset

Dim refRngItemSKU As Excel.Range
Dim LastRowAsIngeger as Integer
Dim INVENTORYTABLE as String
Dim strSelectRS as String

' ************************

LastRowAsInteger = 1764    'Value set in code for now, will be formula later to make dynamic

Set refRngItemSKU = ThisWorkbook.Worksheets("Vendor Inventory").Range("A11:A" & LastRowAsInteger)

' ******* NOTE when I insert refRngItemSKU.select the correct range of cells are selected  **********

INVENTORYTABLE = "D:\My Documents\Leavers Switches And More\INVENTORY\COLLECTIONS AND DISTRIBUTOR  INVENTORY\Model Train Inventory - Updated 6-7-2017.xlsm"

Set db = DBEngine.OpenDatabase(INVENTORYTABLE, False, False, "Excel 12.0;")

strSelectRS = "SELECT * FROM [Vendor Inventory$] WHERE [refrngitemsku$] IS NOT NULL"

Set rst = db.OpenRecordset(strSelectRS)

'**********************************************
END OF CODE

Now everything up to the last line of code works.  When it reaches the "Set rst" line, Error 3061 comes up. The error states "Too Few Parameters. Expected 1".  When I am in Debug mode, I notice the "refrngitemsku" variable is not returning a value in the "strSelectRS" string where the actual value should be showing up.  So any help in correcting the Syntax so I can return a value, ie. the actual range of cells that the refrngItemSKU variable is supposed to return.  Thank you again.  Sorry for having to edit my Question, but the comment section does not allow for enough letters to type all this out.   To the moderators, I appreciate your patience with my posts.  But I am desperate for answers, and so far, this forum is the only one that have been willing to answer my questions! Thanks again.

Ken L.

POSTED EARLIER
GOOD NEWS! Thanks to the suggestion of using ACEDAO.DLL that seems to have resolved the first problem, but a new one has crept up.  I can't find a way to use DAO, in Excel 2013-64, using SQL to query the various tables.  It seems I can not define "Fields" and "Records" whereby the Columns are the "Fields" and the Rows are the "Records".  Though when I do a recordcount on the record set, it shows the total number of rows that have data on them.  But when I try to identify a column (I.e. Field) to set conditions on which records to select, I get syntax errors.  Any help would be much appreciated, and thanks again to all of the posts, they all have been helpful as it caused me to google specific terms to find solutions to my current project! THANK YOU THANK YOU THANK YOU!

Ken L
ORIGINAL POST:
I have searched using google to find a specific answer with no luck.  I keep getting error code 429 when trying to use DAO language "OpenDatabase" so I can use SQL Language to search various worksheets in one Excel 2013 Workbook.  I am running Windows 7-64 and Office 2013 64-bit.  From what I have read, it would appear DAO is not supported anymore by Microsoft, and even ADO doesn't look like it is looked favorably by the folks at Microsoft anymore.  I really don't care if I can't use DAO anymore as long as if there is a method where I can use similar functionality to find specific records based on specific criteria, amend certain records, create other records, and move amongst records  (i.e. .movefirst, .movelast, etc.).  If there is a different VBA language that is usable for 64 bit versions of my software, I will learn it.

I rather not use the workbook, worksheet functions and using IF-THEN statements going through the entire table trying to find certain "records" that match the criteria I am looking for.  It works, but its tedious and I much rather use SQL type language.

I realize using MS Access would be more appropriate, but I prefer using the Spreadsheet format. What I am trying to do is write a VBA program that converts certain cell values into a certain format to be converted to a csv file to upload to a website for my web-store.  The file is my inventory sheet, with tons of calculations/formulas in it.  I rather not use MS Access if I don't have to.

Thank you for any help that can be provided!

Thanks.

Ken L.

答:
You can use ADO:</p>

```<code>Dim conn As New ADODB.Connection
conn.Open("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myOldExcelFile.xls;Extended Properties=""Excel 8.0;HDR=YES"";")
</code>```

Body:
You can use ADO:

Dim conn As New ADODB.Connection
conn.Open("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myOldExcelFile.xls;Extended Properties=""Excel 8.0;HDR=YES"";")


问:
tar: Cowardly refusing to create an empty archive
I use the following tar command to try to backup my entire file system

```<code>tar -cvpzf test/backup.tar.gz --exclude=/test
</code>```

And I receive the following error message

```<code>tar: Cowardly refusing to create an empty archive
Try 'tar --help' or 'tar --usage' for more information.
</code>```

Can somebody point me in the right direction as to how to use tar and explain why it's trying to create an empty archive?

答: You defined what to exclude, but didn't define what you actually want in the archive. Supply at least one path. If you want entire filesystem, then tar -c....... /

Body:
I use the following tar command to try to backup my entire file system

tar -cvpzf test/backup.tar.gz --exclude=/test

And I receive the following error message

tar: Cowardly refusing to create an empty archive
Try 'tar --help' or 'tar --usage' for more information.

Can somebody point me in the right direction as to how to use tar and explain why it's trying to create an empty archive?


问:
BigQuery, left join
I am stuck on a very simple SQL script. I want to do a LEFT JOIN on Google BigQuery.

SELECT a.name, b.name FROM [bigquery-00000:table1] a LEFT JOIN
  [bigquery-00000:table2] b ON b.name = a.name LIMIT 10

And I keep getting an error message:

ON clause must be AND of = comparisons of one field name from each
  table, with all field names prefixed with table name. Consider using
  Standard SQL .google.com/bigquery/docs/reference/standard-sql/), which
  allows non-equality JOINs and comparisons involving expressions and
  residual predicates

I don't understand what is wrong with my script. Please help.

答: I found what was wrong with my script. Wrong table name... sorry.</p>

Title: BigQuery, left join


问:
A Neo4j container (docker) with initial data in it
Other database dockers that I've worked with (like Postgres) have a mechanism to import some initial data into their empty instance once the container starts for the first time. This is usually in form of putting your SQL files in a specific folder.

I need to do the same for Neo4j. I want to compose a Neo4j docker image with some data in it. What's the right way to do this?

答:
This could be achieved...
There are 2 requirements:

set initial password, which could be achieved using bin/neo4j-admin set-initial-password <password> and then

import data from file in cypher format cat import/data.cypher | NEO4J_USERNAME=neo4j NEO4J_PASSWORD=${NEO4J_PASSWD} bin/cypher-shell --fail-fast

Sample Dockerfile may look like this

```<code>FROM neo4j:3.2

ENV NEO4J_PASSWD neo4jadmin
ENV NEO4J_AUTH neo4j/${NEO4J_PASSWD}

COPY data.cypher /var/lib/neo4j/import/

VOLUME /data

CMD bin/neo4j-admin set-initial-password ${NEO4J_PASSWD} || true && \
    bin/neo4j start && sleep 5 && \
    for f in import/*; do \
      [ -f "$f" ] || continue; \
      cat "$f" | NEO4J_USERNAME=neo4j NEO4J_PASSWORD=${NEO4J_PASSWD} bin/cypher-shell --fail-fast && rm "$f"; \
    done && \
    tail -f logs/neo4j.log
</code>```

Building image sudo docker build -t neo4j-3.1:loaddata .

And running container docker run -it --rm --name neo4jtest neo4j-3.1:loaddata

Body:
This could be achieved...
There are 2 requirements:

set initial password, which could be achieved using bin/neo4j-admin set-initial-password <password> and then

import data from file in cypher format cat import/data.cypher | NEO4J_USERNAME=neo4j NEO4J_PASSWORD=${NEO4J_PASSWD} bin/cypher-shell --fail-fast

Sample Dockerfile may look like this

FROM neo4j:3.2

ENV NEO4J_PASSWD neo4jadmin
ENV NEO4J_AUTH neo4j/${NEO4J_PASSWD}

COPY data.cypher /var/lib/neo4j/import/

VOLUME /data

CMD bin/neo4j-admin set-initial-password ${NEO4J_PASSWD} || true && \
    bin/neo4j start && sleep 5 && \
    for f in import/*; do \
      [ -f "$f" ] || continue; \
      cat "$f" | NEO4J_USERNAME=neo4j NEO4J_PASSWORD=${NEO4J_PASSWD} bin/cypher-shell --fail-fast && rm "$f"; \
    done && \
    tail -f logs/neo4j.log

Building image sudo docker build -t neo4j-3.1:loaddata .

And running container docker run -it --rm --name neo4jtest neo4j-3.1:loaddata


问:
C# Webbrowser Invoke Click Issue
I Want to click this button on webbrowser using (invoke click)</p>

```<code><div class="ajax-load">
    <div id="yt0fake" style="display: none"></div>
    <input type="submit" class="gr-button add_request agree" id="59349129dd8aa" name="yt0" value="Something">
</div>

webbrowser.Document.GetElementById("yt0").InvokeMember("click");
webbrowser.Document.GetElementById("yt0fake").InvokeMember("click");
</code>```

答:
You are giving the button a name of "yt0" and then trying to find it by that Id instead.

```<code><input type="submit" class="gr-button add_request agree" id="59349129dd8aa" name="yt0" value="Something">
</code>```

You either need to change the Id from "59349129dd8aa" to "yt0" or use .GetElementByName

To keep the Id the way it is now try this:

```<code> webbrowser.Document.GetElementById("59349129dd8aa").InvokeMember("Click");
</code>```

Or fix the Id and use this

```<code> webbrowser.Document.GetElementById("yt0").InvokeMember("Click");
</code>```

Also notice it is Click not click.

Title: C# Webbrowser Invoke Click Issue

Body:
I Want to click this button on webbrowser using (invoke click)

    <input type="submit" class="gr-button add_request agree" id="59349129dd8aa" name="yt0" value="Something">

webbrowser.Document.GetElementById("yt0").InvokeMember("click");
webbrowser.Document.GetElementById("yt0fake").InvokeMember("click");

Body:
You are giving the button a name of "yt0" and then trying to find it by that Id instead.

<input type="submit" class="gr-button add_request agree" id="59349129dd8aa" name="yt0" value="Something">

You either need to change the Id from "59349129dd8aa" to "yt0" or use .GetElementByName

To keep the Id the way it is now try this:

 webbrowser.Document.GetElementById("59349129dd8aa").InvokeMember("Click");

Or fix the Id and use this

 webbrowser.Document.GetElementById("yt0").InvokeMember("Click");

Also notice it is Click not click.


问:
Where should scripts be located in a jQuery Mobile page for best performance?
Most people recommend scripts tags be placed at the bottom of the page for performance reasons - jQuery: Move JavaScript to the bottom of the page?

How does this practice apply to jQuery Mobile web pages?

Examples I have seen place jQuery and jQuery Mobile scripts in the head tag. Should other scripts be placed in the head tag as well? What is best practice?

答:
While this might not be related to performance as speed, it is important in the jquery mobile context that you properly add scripts to pages. Plain old $(function(){}) will surprise you. It doesn't work in some cases.

When a link is clicked jquery mobile fetches the page with ajax and adds its content to the currently open page ignoring everything you put in the . [This is true as of jqm 1.0a2]

There are two ways of adding scripts that will work:

putting all scripts in a single .js file and link them in the head of all pages of your app and work with events that jqm provides (pageshow and pagecreate ones).

putting scripts at the bottom of the body and NOT require DOMready to fire.

The second way might be better for performance in big applications, where there are a lot of scripts that the user might not use (not visiting certain pages).
I would recommend the first way - it's cleaner and jqm seems to encourage it.

A hybrid of both might be what's best - adding a pageshow event handler thet would trigger some default function from each loaded page.

[edit]

see Limitations here at the bottom of the page.

Body:
While this might not be related to performance as speed, it is important in the jquery mobile context that you properly add scripts to pages. Plain old $(function(){}) will surprise you. It doesn't work in some cases.

When a link is clicked jquery mobile fetches the page with ajax and adds its content to the currently open page ignoring everything you put in the <head>. [This is true as of jqm 1.0a2]

There are two ways of adding scripts that will work:

putting all scripts in a single .js file and link them in the head of all pages of your app and work with events that jqm provides (pageshow and pagecreate ones).

putting scripts at the bottom of the body and NOT require DOMready to fire.

The second way might be better for performance in big applications, where there are a lot of scripts that the user might not use (not visiting certain pages).
I would recommend the first way - it's cleaner and jqm seems to encourage it.

A hybrid of both might be what's best - adding a pageshow event handler thet would trigger some default function from each loaded page.

[edit]

see Limitations here at the bottom of the page.


问:
Using function inside MongoDB query and variable scope
I want to code a little app where I can store the incoming request url, named reqUrl below, and check if it already exists by using the compareUrls function.

It returns true if both websites are in the same domain and false otherwise, for example when doing compareUrls(stackoverflow.com, http://www.stackoverflow.com). This is used so as not to add duplicate urls.

I am trying to use that function inside a MongoDB query like this:

```<code>app.get("/:reqUrl", function(req, res)
{
    var reqUrl = req.params.reqUrl;

    MongoClient.connect(Url, function(err, db)
     {
       if (err) throw err;
       db.collection("mydb").find({$where: function() {

         if (compareUrls(reqUrl, this.url) //if true, simply return the url
         {
            return this.url;
         } else { //if not existing insert it into the database
            db.collection("mydb").insert({"url":reqUrl});
         };

     }}).toArray();

//Code continues below
</code>```

Now the problem is that because of scoping, the reqUrl variable is not recognized, and I don't know any workaround. And even when using local variables with compareUrls I get back the whole collection of elements. I thought about retrieving back all results to an array by simply calling .find and checking reqUrl against each item, but that would be far more than efficient.

Please note that I am very new to MongoDB.

Any feedback would be appreciated, thanks.

答:
The bottom line here is that you cannot perform other database operations inside the logic of a $where clause, nor should you since it is completely unnecessary and your actions are actually supported in existing standard operators and methods.

What you really want here is .findOneAndUpdate(). You do not need $where for the sort of match condition you are doing which is to simply check a value. This is actually a $regex search condition for the "query" portion to select.

As for the "insert" part, then that is what "upserts" are for. So when the data is not "found", then the "upsert" creates/inserts the new document in the collection, otherwise when found it "updates". You can tune that in this case with the $setOnInsert modifier so that a "found" document is not actually modified, and the data is only touched on "insertion":

```<code>db.collection("mydb").findOneAndUpdate(
  { "url": new RegExp(reqUrl) },
  { "$setOnInsert": { "url": reqUrl } },
  { "upsert": true, "returnOriginal": false },
  function(err, doc) {
    // deal with result here
  }
)
</code>```

Of course the $regex usage here is just a basic "is this string present in the properties string" condition. There are more advanced regular expressions specific to "domain matching", such as you could find in the existing answers here: Regex to match simple domain

But the basic logic remains the same that a "regular expression" does the match condition and then you simply "upsert".

That said, there is nothing actually stopping you from using a $where clause for the match condition. It's just that the actual operation remains an "upsert" instead of trying to call a database method "within" the supplied function which can either call a server function or be included inline:

```<code>db.collection("mydb").findOneAndUpdate(
  { "$where": function() { return compareUrls(reqUrl, this.url); }  },
  { "$setOnInsert": { "url": reqUrl } },
  { "upsert": true, "returnOriginal": false },
  function(err, doc) {
    // deal with result here
  }
)
</code>```

Just make sure that under the conditions of $where the server function or any result is actually returning a boolean true/false, since that is how $where operates.

Also note the usage of "returnOriginal": false here, as the default behavior of the .findOneAndUpdate() method is to return the "original" document before modification. In some cases this would be desired, but most common usage is to return the document in it's modified state.

Of course if you do not need the document in response at all, then .updateOne() will suffice as a method, and reduces the overhead of returning the document content "over the wire".

Body:
I want to code a little app where I can store the incoming request url, named reqUrl below, and check if it already exists by using the compareUrls function.

It returns true if both websites are in the same domain and false otherwise, for example when doing compareUrls(stackoverflow.com, http://www.stackoverflow.com). This is used so as not to add duplicate urls.

I am trying to use that function inside a MongoDB query like this:

app.get("/:reqUrl", function(req, res)
{
    var reqUrl = req.params.reqUrl;

    MongoClient.connect(Url, function(err, db)
     {
       if (err) throw err;
       db.collection("mydb").find({$where: function() {

         if (compareUrls(reqUrl, this.url) //if true, simply return the url
         {
            return this.url;
         } else { //if not existing insert it into the database
            db.collection("mydb").insert({"url":reqUrl});
         };

     }}).toArray();

//Code continues below

Now the problem is that because of scoping, the reqUrl variable is not recognized, and I don't know any workaround. And even when using local variables with compareUrls I get back the whole collection of elements. I thought about retrieving back all results to an array by simply calling .find and checking reqUrl against each item, but that would be far more than efficient.

Please note that I am very new to MongoDB.

Any feedback would be appreciated, thanks.

Body:
The bottom line here is that you cannot perform other database operations inside the logic of a $where clause, nor should you since it is completely unnecessary and your actions are actually supported in existing standard operators and methods.

What you really want here is .findOneAndUpdate(). You do not need $where for the sort of match condition you are doing which is to simply check a value. This is actually a $regex search condition for the "query" portion to select.

As for the "insert" part, then that is what "upserts" are for. So when the data is not "found", then the "upsert" creates/inserts the new document in the collection, otherwise when found it "updates". You can tune that in this case with the $setOnInsert modifier so that a "found" document is not actually modified, and the data is only touched on "insertion":

db.collection("mydb").findOneAndUpdate(
  { "url": new RegExp(reqUrl) },
  { "$setOnInsert": { "url": reqUrl } },
  { "upsert": true, "returnOriginal": false },
  function(err, doc) {
    // deal with result here
  }
)

Of course the $regex usage here is just a basic "is this string present in the properties string" condition. There are more advanced regular expressions specific to "domain matching", such as you could find in the existing answers here: Regex to match simple domain

But the basic logic remains the same that a "regular expression" does the match condition and then you simply "upsert".

That said, there is nothing actually stopping you from using a $where clause for the match condition. It's just that the actual operation remains an "upsert" instead of trying to call a database method "within" the supplied function which can either call a server function or be included inline:

db.collection("mydb").findOneAndUpdate(
  { "$where": function() { return compareUrls(reqUrl, this.url); }  },
  { "$setOnInsert": { "url": reqUrl } },
  { "upsert": true, "returnOriginal": false },
  function(err, doc) {
    // deal with result here
  }
)

Just make sure that under the conditions of $where the server function or any result is actually returning a boolean true/false, since that is how $where operates.

Also note the usage of "returnOriginal": false here, as the default behavior of the .findOneAndUpdate() method is to return the "original" document before modification. In some cases this would be desired, but most common usage is to return the document in it's modified state.

Of course if you do not need the document in response at all, then .updateOne() will suffice as a method, and reduces the overhead of returning the document content "over the wire".


问:
How do I change an attribute or class using only Javascript?
I would like to change the styling attribute values of all elements that have the class "post-feature" and contain an attribute value of "http"

So the div element will look like the following:

So far the http check works. But I am not able to set the attribute value.

I have the following code

```<code>var features = document.getElementsByClassName(".post-feature")
[0].getAttribute("style");

if (features.includes("http")) {
features.setAttribute("background-color", "orange");

} else {

  alert('no change');

}
</code>```

答:
Use element.style.backgroundColor and indexOf

```<code>var features = document.getElementsByClassName(".post-feature")[0].getAttribute("style");

if (features.indexOf("http") > -1) {

  features.style.backgroundColor = "orange";

} else {

  alert('no change');

}
</code>```

Body:
I would like to change the styling attribute values of all elements that have the class "post-feature" and contain an attribute value of "http"

So the div element will look like the following:

So far the http check works. But I am not able to set the attribute value.

I have the following code

var features = document.getElementsByClassName(".post-feature")
[0].getAttribute("style");

if (features.includes("http")) {
features.setAttribute("background-color", "orange");

} else {

  alert('no change');

}

Body:
Use element.style.backgroundColor and indexOf

var features = document.getElementsByClassName(".post-feature")[0].getAttribute("style");

if (features.indexOf("http") > -1) {

  features.style.backgroundColor = "orange";

} else {

  alert('no change');

}


问:
Java - Check if array contains 3 consecutive dates
Hi I have a String[] array that contains dates in the format YYYY/MM/DD. I want to iterate through this array and see if the next 2 elements in the array contain consecutive dates. If they do then just increase the count variable. Here is what I have so far. I just basically need help regarding the if statement that checks if there are 3 consecutive dates.

```<code>int count = 0;

String[] dates = {
        "2004/1/23", "2004/1/24", "2004/1/25",
        "2004/1/26", "2004/1/29", "2004/2/11",
        "2004/2/17", "2004/2/18", "2004/2/18", "2004/3/7"};

for(int i = 0; i < dates.length-2; i++){

    //Help needed here! If i, i+1 and i+2 are consecutive...
    if(...){
        count++;
    }
}
</code>```

I realise that I might need to convert the String dates into an actual Date object before I can compare them. Further guidance would be appreciated. Thanks

答:
tl;dr

Use java.time.LocalDate class.

```<code>if ( z.minusDays ( 1 ).isEqual ( y ) && z.minusDays ( 2 ).isEqual ( x ) )  …
</code>```

Using java.time

The modern approach uses the java.time classes rather than the troublesome old legacy classes Date & Calendar.

First convert your array to a list of LocalDate objects. I changed your example data as I assume you meant the 18th and 19th of February rather than repeating the 18th twice.

```<code>String[] dates = {
        "2004/1/23" , "2004/1/24" , "2004/1/25" ,
        "2004/1/26" , "2004/1/29" , "2004/2/11" ,
        "2004/2/17" , "2004/2/18" , "2004/2/19" , "2004/3/7" };

DateTimeFormatter f = DateTimeFormatter.ofPattern ( "uuuu/M/d" );
List < LocalDate > localdates = new ArrayList <> ( dates.length );
for ( String input : dates ) {
    LocalDate ld = LocalDate.parse ( input, f );
    localdates.add ( ld );
}
</code>```

Loop the LocalDate list, remembering the previous two items. If the current and the previous two are all sequential dates, then increment your counter.

```<code>Integer tripletCount = 0;
List< LocalDate > tripletDates = new ArrayList<>();
LocalDate x = null;
LocalDate y = null;
for ( LocalDate z : localdates ) {
    if ( null == x ) { x = z; continue; }
    if ( null == y ) { y = z; continue; }
    if ( z.minusDays ( 1 ).isEqual ( y ) && z.minusDays ( 2 ).isEqual ( x ) ) {
        tripletCount= ( tripletCount + 1 );
        tripletDates.add( z );
    }
    // Prepare for next loop.
    x = y ;
    y = z ;
}
</code>```

Dump to console.

```<code>System.out.println ( "localdates: " + localdates );
System.out.println ( "tripletCount: " + tripletCount );
System.out.println ( "tripletDates: " + tripletDates );
</code>```

localdates: [2004-01-23, 2004-01-24, 2004-01-25, 2004-01-26, 2004-01-29, 2004-02-11, 2004-02-17, 2004-02-18, 2004-02-19, 2004-03-07]

tripletCount: 3

tripletDates: [2004-01-25, 2004-01-26, 2004-02-19]

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

Java SE 8, Java SE 9, and later

Built-in.

Part of the standard Java API with a bundled implementation.

Java 9 adds some minor features and fixes.

Java SE 6 and Java SE 7

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

Android

The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.

See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Body:
Hi I have a String[] array that contains dates in the format YYYY/MM/DD. I want to iterate through this array and see if the next 2 elements in the array contain consecutive dates. If they do then just increase the count variable. Here is what I have so far. I just basically need help regarding the if statement that checks if there are 3 consecutive dates.

int count = 0;

String[] dates = {
        "2004/1/23", "2004/1/24", "2004/1/25",
        "2004/1/26", "2004/1/29", "2004/2/11",
        "2004/2/17", "2004/2/18", "2004/2/18", "2004/3/7"};

for(int i = 0; i < dates.length-2; i++){

    //Help needed here! If i, i+1 and i+2 are consecutive...
    if(...){
        count++;
    }
}

I realise that I might need to convert the String dates into an actual Date object before I can compare them. Further guidance would be appreciated. Thanks

Body:
tl;dr

Use java.time.LocalDate class.

if ( z.minusDays ( 1 ).isEqual ( y ) && z.minusDays ( 2 ).isEqual ( x ) )  …

Using java.time

The modern approach uses the java.time classes rather than the troublesome old legacy classes Date & Calendar.

First convert your array to a list of LocalDate objects. I changed your example data as I assume you meant the 18th and 19th of February rather than repeating the 18th twice.

String[] dates = {
        "2004/1/23" , "2004/1/24" , "2004/1/25" ,
        "2004/1/26" , "2004/1/29" , "2004/2/11" ,
        "2004/2/17" , "2004/2/18" , "2004/2/19" , "2004/3/7" };

DateTimeFormatter f = DateTimeFormatter.ofPattern ( "uuuu/M/d" );
List < LocalDate > localdates = new ArrayList <> ( dates.length );
for ( String input : dates ) {
    LocalDate ld = LocalDate.parse ( input, f );
    localdates.add ( ld );
}

Loop the LocalDate list, remembering the previous two items. If the current and the previous two are all sequential dates, then increment your counter.

Integer tripletCount = 0;
List< LocalDate > tripletDates = new ArrayList<>();
LocalDate x = null;
LocalDate y = null;
for ( LocalDate z : localdates ) {
    if ( null == x ) { x = z; continue; }
    if ( null == y ) { y = z; continue; }
    if ( z.minusDays ( 1 ).isEqual ( y ) && z.minusDays ( 2 ).isEqual ( x ) ) {
        tripletCount= ( tripletCount + 1 );
        tripletDates.add( z );
    }
    // Prepare for next loop.
    x = y ;
    y = z ;
}

Dump to console.

System.out.println ( "localdates: " + localdates );
System.out.println ( "tripletCount: " + tripletCount );
System.out.println ( "tripletDates: " + tripletDates );

localdates: [2004-01-23, 2004-01-24, 2004-01-25, 2004-01-26, 2004-01-29, 2004-02-11, 2004-02-17, 2004-02-18, 2004-02-19, 2004-03-07]

tripletCount: 3

tripletDates: [2004-01-25, 2004-01-26, 2004-02-19]

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

Java SE 8, Java SE 9, and later

Built-in.

Part of the standard Java API with a bundled implementation.

Java 9 adds some minor features and fixes.

Java SE 6 and Java SE 7

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

Android

The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.

See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


问:
Caliburn.Micro's OnUnhandledException not called
I have overridden the OnUnhandledException in my bootstrapper, but in the following scenario it is not called:

```<code>public class Foo : IHandle<Bar> {
    public void Handle(Bar message) {
        // Do something that requires UI thread
    }

    public void DoSomething() {
        eventAggregator.PublishOnBackgroundThread(new Bar());
    }
}
</code>```

When the handle method is called it will throw InvalidOperationException: The calling thread must be STA, because many UI components require this. because it is performed on the background thread instead of on the UI thread:

That exception is never caught by OnUnhandledException in my bootstrapper. Neither is it caught by the Application.DispatcherUnhandledException event handler.

How can I make a general exception handler that will also catch these types of exceptions, without having to implement try/catch everywhere?

答:
It looks like this is a problem with background threads and WPF not making it to the event handler.

The linked question has a solution, but it's may be something we (Caliburn.Micro) can help with.

Body:
I have overridden the OnUnhandledException in my bootstrapper, but in the following scenario it is not called:

public class Foo : IHandle<Bar> {
    public void Handle(Bar message) {
        // Do something that requires UI thread
    }

    public void DoSomething() {
        eventAggregator.PublishOnBackgroundThread(new Bar());
    }
}

When the handle method is called it will throw InvalidOperationException: The calling thread must be STA, because many UI components require this. because it is performed on the background thread instead of on the UI thread:

That exception is never caught by OnUnhandledException in my bootstrapper. Neither is it caught by the Application.DispatcherUnhandledException event handler.

How can I make a general exception handler that will also catch these types of exceptions, without having to implement try/catch everywhere?


问:
Parent fragment to Child Fragment communication
I have been searching and haven't found the best way for nested fragments to communicate with parent fragment. The Android documentation states that:

All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.

Suppose I have a Gallery app, there is a ViewPagerFragment (parent) and ImageFragment(child) that is used to show images full screen when they are clicked. I need to pass an ArrayList of Files from my parent fragment to the child fragment. What is a proper way to do it?

1) Create a getter for the ArrayList in parent fragment and use the getParentFragment() in a child fragment to access this method?

2) Implement an interface and go through the Activity, but how will I locate the child fragment from the Activity if it doesn't have an ID?

3) Or use this in parent fragment:

ChildFragment fragment =(ChildFragment)getChildFragmentManager().findFragmentById(R.id.child_fragment_id);

And just use a setter in child fragment.

But again how do I get the ID of the childFragment?

Thanks everyone in advance

答:
If you want to communicate with your child Fragment to your parent Fragment you can use getParentFragment() method from your child fragment.

Example

```<code>public class ExampleParentFragment extends Fragment {

    public int getCount() {
        return 10;
    }
}

public class ChildFragment extends Fragment {

    void doAction() {
        Fragment parentFragment = getParentFragment();

        if(parentFragment instanceof ExampleParentFragment) {
            int count = ((ExampleParentFragment) parentFragment).getCount();
        }
    }
}
</code>```

Body:
If you want to communicate with your child Fragment to your parent Fragment you can use getParentFragment() method from your child fragment.

Example

public class ExampleParentFragment extends Fragment {

    public int getCount() {
        return 10;
    }
}

public class ChildFragment extends Fragment {

    void doAction() {
        Fragment parentFragment = getParentFragment();

        if(parentFragment instanceof ExampleParentFragment) {
            int count = ((ExampleParentFragment) parentFragment).getCount();
        }
    }
}


问:
Writing and reading XML in C#
I've written a setting file in C# as XML

```<code>XmlWriter xmlWriter = XmlWriter.Create(files);
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("Settings");

xmlWriter.WriteStartElement("launch");
xmlWriter.WriteString("launch tab");
xmlWriter.WriteEndElement();

xmlWriter.WriteStartElement("some_setting");
xmlWriter.WriteString("empty");
xmlWriter.WriteEndElement();
</code>```

And so on, but how to read it back?

I keep getting errors.

```<code>XmlReader xmlReader = XmlReader.Create(files);

xmlReader.ReadStartElement("launch");
textBox1.Text = xmlReader.ReadString();
</code>```

I wish to simply read it back in but getting the error

System.Xml.XmlException: 'Element 'launch' was not found

Line 1, position 40.

答:
Of the many ways to parse an XML file (see here for a decent breakdown of the ways), in general I find parsing with an XmlDocument to be more straightforward. For your code it would be something similar to the example below:

```<code>void CreateXML(string fileName)
{
    XmlWriter xmlWriter = XmlWriter.Create(fileName);
    xmlWriter.WriteStartDocument();
    xmlWriter.WriteStartElement("Settings");

    xmlWriter.WriteStartElement("launch");
    xmlWriter.WriteString("launch tab");
    xmlWriter.WriteEndElement();

    xmlWriter.WriteStartElement("some_setting");
    xmlWriter.WriteString("empty");
    xmlWriter.WriteEndElement();

    xmlWriter.WriteEndElement();
    xmlWriter.WriteEndDocument();
    xmlWriter.Close();
}

void ReadXML(string fileName)
{
    XmlDocument doc = new XmlDocument();
    doc.Load(fileName);
    XmlNode root = doc.SelectSingleNode("Settings");
    string launchSetting = root.SelectSingleNode("launch").InnerText;
    textBox1.Text = launchSetting;
}
</code>```

If you want to stick with the XmlReader, I haven't used it before but as Alexei says in his answer it appears that you're not reading in the Settings node start (see below).

```<code>XmlReader xmlReader = XmlReader.Create(files);

xmlReader.ReadStartElement("Settings");

xmlReader.ReadStartElement("launch");
textBox1.Text = xmlReader.ReadString();
</code>```

Title: Writing and reading XML in C#

Body:
I've written a setting file in C# as XML

XmlWriter xmlWriter = XmlWriter.Create(files);
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("Settings");

xmlWriter.WriteStartElement("launch");
xmlWriter.WriteString("launch tab");
xmlWriter.WriteEndElement();

xmlWriter.WriteStartElement("some_setting");
xmlWriter.WriteString("empty");
xmlWriter.WriteEndElement();

And so on, but how to read it back?

I keep getting errors.

XmlReader xmlReader = XmlReader.Create(files);

xmlReader.ReadStartElement("launch");
textBox1.Text = xmlReader.ReadString();

I wish to simply read it back in but getting the error

System.Xml.XmlException: 'Element 'launch' was not found

Line 1, position 40.

Body:
Of the many ways to parse an XML file (see here for a decent breakdown of the ways), in general I find parsing with an XmlDocument to be more straightforward. For your code it would be something similar to the example below:

void CreateXML(string fileName)
{
    XmlWriter xmlWriter = XmlWriter.Create(fileName);
    xmlWriter.WriteStartDocument();
    xmlWriter.WriteStartElement("Settings");

    xmlWriter.WriteStartElement("launch");
    xmlWriter.WriteString("launch tab");
    xmlWriter.WriteEndElement();

    xmlWriter.WriteStartElement("some_setting");
    xmlWriter.WriteString("empty");
    xmlWriter.WriteEndElement();

    xmlWriter.WriteEndElement();
    xmlWriter.WriteEndDocument();
    xmlWriter.Close();
}

void ReadXML(string fileName)
{
    XmlDocument doc = new XmlDocument();
    doc.Load(fileName);
    XmlNode root = doc.SelectSingleNode("Settings");
    string launchSetting = root.SelectSingleNode("launch").InnerText;
    textBox1.Text = launchSetting;
}

If you want to stick with the XmlReader, I haven't used it before but as Alexei says in his answer it appears that you're not reading in the Settings node start (see below).

XmlReader xmlReader = XmlReader.Create(files);

xmlReader.ReadStartElement("Settings");

xmlReader.ReadStartElement("launch");
textBox1.Text = xmlReader.ReadString();


问:
ASP.NET MVC multiple begin forms?
Hi I am using multiple begin forms. I am not sure if this is a good Idea. This is my code.

```<code><% using (Html.BeginForm("TagManagement", "InternalTag",FormMethod.Post))
   {%>
   <%: Html.AntiForgeryToken() %>

    <table>
        <tr>
            <td><%:Html.Label("Type") %></td>
            <td style="text-align:left"><%:Html.DropDownList("ObjectType",ViewData["TagObjects"] as IEnumerable<SelectListItem>)%></td>
        </tr>
        <tr>
            <td><%:Html.Label("Search ID")%></td>
            <td style="text-align:left"><%:Html.TextBox("ObjectID2")%></td>
        </tr>
        <tr>
            <td></td>
            <td><input id="Search" type="submit" value="Search" />   <input id="Create" type="button" value="Add to New Tag" onclick="AddTagElements()" /></td>
        </tr>
    </table>
    <br />

<% } %>

<% using (Html.BeginForm("CreateTag","InternalTag",FormMethod.Post)) { %>
<%: Html.AntiForgeryToken() %>
<div id="AddTag">
      <input id='SaveTag' type='submit' value='Save' style='width: 125px' />
</div>
<% } %>
</code>```

routing code

```<code>"Tags/{controller}/{action}/{id}/{type}",
new { action = "Index", id = UrlParameter.Optional, type = UrlParameter.Optional }
</code>```

my controller methods:

```<code>public ActionResult TagManagement(FormCollection FC,Guid? ID,InternalTagRef_Types? Type)
public ActionResult CreateTag(FormCollection FC, Guid ID, InternalTagRef_Types Type)
</code>```

when I click on search TagManagement Actions parameters get properly populated. When I click on SaveTag it tries call the CreateTag action but cannot because it is missing ID and Type. I get the error The parameters dictionary contains a null entry for parameter 'ID' of non-nullable type 'System.Guid'. It should get these values from the URL i.e.
http://localhost:1338/Tags/InternalTag/TagManagement/D104EBF5-470B-4FAA-9FC7-5391922CCE94/Projects like TagManagement.  Please help.

答:
Your second form contains no input fields (other than a submit button) so when the form is submitted nothing is sent to the server and the controller action has nothing to bind from. So you will need to include text fields or hidden fields as you did in your first form.

UPDATE:

You cold include route parameters in the generated action:

```<code><% using (Html.BeginForm(
        "CreateTag", "InternalTag",
        new { id = RouteData.Values["id"], type = RouteData.Values["type"] },
        FormMethod.Post)) { %>
    <%: Html.AntiForgeryToken() %>
    <div id="AddTag">
        <input id='SaveTag' type='submit' value='Save' style='width: 125px' />
    </div>
<% } %>
</code>```

Title: ASP.NET MVC multiple begin forms?

Body:
Hi I am using multiple begin forms. I am not sure if this is a good Idea. This is my code.

<% using (Html.BeginForm("TagManagement", "InternalTag",FormMethod.Post))
   {%>
   <%: Html.AntiForgeryToken() %>

            <%:Html.Label("Type") %>
            <%:Html.DropDownList("ObjectType",ViewData["TagObjects"] as IEnumerable<SelectListItem>)%>

            <%:Html.Label("Search ID")%>
            <%:Html.TextBox("ObjectID2")%>

            <input id="Search" type="submit" value="Search" />   <input id="Create" type="button" value="Add to New Tag" onclick="AddTagElements()" />

<% } %>

<% using (Html.BeginForm("CreateTag","InternalTag",FormMethod.Post)) { %>
<%: Html.AntiForgeryToken() %>

      <input id='SaveTag' type='submit' value='Save' style='width: 125px' />

<% } %>

routing code

"Tags/{controller}/{action}/{id}/{type}",
new { action = "Index", id = UrlParameter.Optional, type = UrlParameter.Optional }

my controller methods:

public ActionResult TagManagement(FormCollection FC,Guid? ID,InternalTagRef_Types? Type)
public ActionResult CreateTag(FormCollection FC, Guid ID, InternalTagRef_Types Type)

when I click on search TagManagement Actions parameters get properly populated. When I click on SaveTag it tries call the CreateTag action but cannot because it is missing ID and Type. I get the error The parameters dictionary contains a null entry for parameter 'ID' of non-nullable type 'System.Guid'. It should get these values from the URL i.e.
http://localhost:1338/Tags/InternalTag/TagManagement/D104EBF5-470B-4FAA-9FC7-5391922CCE94/Projects like TagManagement.  Please help.

Body:
Your second form contains no input fields (other than a submit button) so when the form is submitted nothing is sent to the server and the controller action has nothing to bind from. So you will need to include text fields or hidden fields as you did in your first form.

UPDATE:

You cold include route parameters in the generated action:

<% using (Html.BeginForm(
        "CreateTag", "InternalTag",
        new { id = RouteData.Values["id"], type = RouteData.Values["type"] },
        FormMethod.Post)) { %>
    <%: Html.AntiForgeryToken() %>
    <div id="AddTag">
        <input id='SaveTag' type='submit' value='Save' style='width: 125px' />
    </div>
<% } %>