问:
Shift/Reduce conflict in CUP
I'm trying to write a parser for a javascript-ish language with JFlex and Cup, but I'm having some issues with those deadly shift/reduce problems and reduce/reduce problems.

I have searched thoroughly and have found tons of examples, but I'm not able to extrapolate these to my grammar. My understanding so far is that these problems are because the parser cannot decide which way it should take because it can't distinguish.

My grammar is the following one:
        start with INPUT;

```<code>INPUT::= PROGRAM;

PROGRAM::= FUNCTION NEWLINE PROGRAM
| NEWLINE PROGRAM;

FUNCTION ::= function OPTIONAL id p_izq ARG p_der NEWLINE l_izq NEWLINE BODY l_der;

    OPTIONAL ::=
    | TYPE;

    TYPE::= integer
    | boolean

    ARG ::=
    | TYPE id MORE_ARGS;

    MORE_ARGS ::=
    | colon TYPE id MORE_ARGS;

    NEWLINE ::= salto NEWLINE
    | ;

    BODY ::=  ;
</code>```

I'm getting several conflicts but these 2 are a mere example:

```<code> Warning : *** Shift/Reduce conflict found in state #5
 between NEWLINE ::= (*)
 and     NEWLINE ::= (*) salto NEWLINE
 under symbol salto
 Resolved in favor of shifting.

 Warning : *** Shift/Reduce conflict found in state #0
 between NEWLINE ::= (*)
 and     FUNCTION ::= (*) function OPTIONAL id p_izq ARG p_der NEWLINE l_izq NEWLINE BODY l_der
 under symbol function
 Resolved in favor of shifting.
</code>```

PS: The grammar is far more complex, but I think that if I see how these shift/reduce problems are solved, I'll be able to fix the rest.

Thanks for your answers.

答:
PROGRAM is useless (in the technical sense). That is, it cannot produce any sentence because in

```<code>PROGRAM::= FUNCTION NEWLINE PROGRAM
       |   NEWLINE PROGRAM;
</code>```

both productions for PROGRAM are recursive. For a non-terminal to be useful, it needs to be able to eventually produce some string of terminals, and for it to do that, it must have at least one non-recursive production; otherwise, the recursion can never terminate. I'm surprised CUP didn't mention this to you. Or maybe it did, and you chose to ignore the warning.

That's a problem -- useless non-terminals really cannot ever match anything, so they will eventually result in a parse error -- but it's not the parsing conflict you're reporting. The conflicts come from another feature of the same production, which is related to the fact that you can't divide by 0.

The thing about nothing is that any number of nothings are still nothing. So if you had plenty of nothings and someone came along and asked you exactly how many nothings you had, you'd have a bit of problem, because to get "plenty" back from "0 * plenty", you'd have to compute "0 / 0", and that's not a well-defined value. (If you had plenty of two's, and someone asked you how many two's you had, that wouldn't be a problem: suppose the plenty of two's worked out to 40; you could easily compute that 40 / 2 = 20, which works out perfectly because 20 * 2 = 40.)

So here we don't have arithmetic, we have strings of symbols. And unfortunately the string containing no symbols is really invisible, like 0 was for all those millenia until some Arabian mathematician noticed the value of being able to write nothing.

Where this is all coming around to is that you have

```<code>PROGRAM::= ... something ...
       |   NEWLINE PROGRAM;
</code>```

But NEWLINE is allowed to produce nothing.

```<code>NEWLINE ::= salto NEWLINE
        |   ;
</code>```

So the second recursive production of PROGRAM might add nothing. And it might add nothing plenty of times, because the production is recursive. But the parser needs to be deterministic: it needs to know exactly how many nothings are present, so that it can reduce each nothing to a NEWLINE non-terminal and then reduce a new PROGRAM non-terminal. And it really doesn't know how many nothings to add.

In short, optional nothings and repeated nothings are ambiguous. If you are going to insert a nothing into your language, you need to make sure that there are a fixed finite number of nothings, because that's the only way the parser can unambiguously dissect nothingness.

Now, since the only point of that particular recursion (as far as I can see) is to allow empty newline-terminated statements (which are visible because of the newline, but do nothing). And you could do that by changing the recursion to avoid nothing:

```<code>PROGRAM ::= ...
        |   salto PROGRAM;
</code>```

Although it's not relevant to your current problem, I feel obliged to mention that CUP is an LALR parser generator and all that stuff you might have learned or read on the internet about recursive descent parsers not being able to handle left recursion does not apply. (I deleted a rant about the way parsing technique are taught, so you'll have to try to recover it from the hints I've left behind.) Bottom-up parser generators like CUP and yacc/bison love left recursion. They can handle right recursion, too, of course, but reluctantly because they need to waste stack space for every recursion other than left recursion. So there is no need to warp your grammar in order to deal with the deficiency; just write the grammar naturally and be happy. (So you rarely if ever need non-terminals representing "the rest of" something.)

PD: Plenty of nothing is a culturally-specific reference to a song from the 1934 opera Porgy and Bess.

Title: Shift/Reduce conflict in CUP

Body:
I'm trying to write a parser for a javascript-ish language with JFlex and Cup, but I'm having some issues with those deadly shift/reduce problems and reduce/reduce problems.

I have searched thoroughly and have found tons of examples, but I'm not able to extrapolate these to my grammar. My understanding so far is that these problems are because the parser cannot decide which way it should take because it can't distinguish.

My grammar is the following one:
        start with INPUT;

INPUT::= PROGRAM;

PROGRAM::= FUNCTION NEWLINE PROGRAM
| NEWLINE PROGRAM;

FUNCTION ::= function OPTIONAL id p_izq ARG p_der NEWLINE l_izq NEWLINE BODY l_der;

    OPTIONAL ::=
    | TYPE;

    TYPE::= integer
    | boolean

    ARG ::=
    | TYPE id MORE_ARGS;

    MORE_ARGS ::=
    | colon TYPE id MORE_ARGS;

    NEWLINE ::= salto NEWLINE
    | ;

    BODY ::=  ;

I'm getting several conflicts but these 2 are a mere example:

 Warning : *** Shift/Reduce conflict found in state #5
 between NEWLINE ::= (*)
 and     NEWLINE ::= (*) salto NEWLINE
 under symbol salto
 Resolved in favor of shifting.

 Warning : *** Shift/Reduce conflict found in state #0
 between NEWLINE ::= (*)
 and     FUNCTION ::= (*) function OPTIONAL id p_izq ARG p_der NEWLINE l_izq NEWLINE BODY l_der
 under symbol function
 Resolved in favor of shifting.

PS: The grammar is far more complex, but I think that if I see how these shift/reduce problems are solved, I'll be able to fix the rest.

Thanks for your answers.

Body:
PROGRAM is useless (in the technical sense). That is, it cannot produce any sentence because in

PROGRAM::= FUNCTION NEWLINE PROGRAM
       |   NEWLINE PROGRAM;

both productions for PROGRAM are recursive. For a non-terminal to be useful, it needs to be able to eventually produce some string of terminals, and for it to do that, it must have at least one non-recursive production; otherwise, the recursion can never terminate. I'm surprised CUP didn't mention this to you. Or maybe it did, and you chose to ignore the warning.

That's a problem -- useless non-terminals really cannot ever match anything, so they will eventually result in a parse error -- but it's not the parsing conflict you're reporting. The conflicts come from another feature of the same production, which is related to the fact that you can't divide by 0.

The thing about nothing is that any number of nothings are still nothing. So if you had plenty of nothings and someone came along and asked you exactly how many nothings you had, you'd have a bit of problem, because to get "plenty" back from "0 * plenty", you'd have to compute "0 / 0", and that's not a well-defined value. (If you had plenty of two's, and someone asked you how many two's you had, that wouldn't be a problem: suppose the plenty of two's worked out to 40; you could easily compute that 40 / 2 = 20, which works out perfectly because 20 * 2 = 40.)

So here we don't have arithmetic, we have strings of symbols. And unfortunately the string containing no symbols is really invisible, like 0 was for all those millenia until some Arabian mathematician noticed the value of being able to write nothing.

Where this is all coming around to is that you have

PROGRAM::= ... something ...
       |   NEWLINE PROGRAM;

But NEWLINE is allowed to produce nothing.

NEWLINE ::= salto NEWLINE
        |   ;

So the second recursive production of PROGRAM might add nothing. And it might add nothing plenty of times, because the production is recursive. But the parser needs to be deterministic: it needs to know exactly how many nothings are present, so that it can reduce each nothing to a NEWLINE non-terminal and then reduce a new PROGRAM non-terminal. And it really doesn't know how many nothings to add.

In short, optional nothings and repeated nothings are ambiguous. If you are going to insert a nothing into your language, you need to make sure that there are a fixed finite number of nothings, because that's the only way the parser can unambiguously dissect nothingness.

Now, since the only point of that particular recursion (as far as I can see) is to allow empty newline-terminated statements (which are visible because of the newline, but do nothing). And you could do that by changing the recursion to avoid nothing:

PROGRAM ::= ...
        |   salto PROGRAM;

Although it's not relevant to your current problem, I feel obliged to mention that CUP is an LALR parser generator and all that stuff you might have learned or read on the internet about recursive descent parsers not being able to handle left recursion does not apply. (I deleted a rant about the way parsing technique are taught, so you'll have to try to recover it from the hints I've left behind.) Bottom-up parser generators like CUP and yacc/bison love left recursion. They can handle right recursion, too, of course, but reluctantly because they need to waste stack space for every recursion other than left recursion. So there is no need to warp your grammar in order to deal with the deficiency; just write the grammar naturally and be happy. (So you rarely if ever need non-terminals representing "the rest of" something.)

PD: Plenty of nothing is a culturally-specific reference to a song from the 1934 opera Porgy and Bess.


来源: stackexchange

问:
Junit testing for a function
I have a confusion regarding Junit testing.For some functions(add function) with closed business logic we can make unit testing by asserting the function.

For example

```<code>public int add(int a,int b){
  int c = a+b;
  return c;
}
</code>```

But for some function(as below example) in a route what methodology we have to do.

For example

```<code>public int foo(int totalnum){
  Zoo soo = new Zoo();
  int giraffNumber = soo.giraffe(totalnum);//here we are calling another method
  return giraffNumber;
}
</code>```

For these kind of methods what approach we have to do.Does we need to write another class.

Can anybody please advise me with an example.

答:
The dogmatic approach to unit testing is that you have to test only one thing at a time, which means that you are not allowed to use new in code to be tested, because this necessarily creates one more thing in addition to the thing that you have set out to test.

The way around this problem is Dependency Injection.  This means that instead of your code reaching out there to fetch its dependencies, (an example of which is using new to create a class that your code wants to use,) your code is supplied its dependencies from the outside.

So, in the case of foo(), that would mean either passing an instance of Zoo as a parameter to foo(), or, better yet, passing a Zoo factory as a constructor parameter to the class that contains foo(), so that then foo() can invoke the factory to obtain an instance of Zoo.

This way, you can pass a specially made implementation of Zoo to use for testing, such as one created with the help of mockito.

Of course, there is also the non-dogmatic approach to unit testing, which says that you should view each thing to be tested as a black box, and not worry about how it is implemented, and instead only worry about obtaining the correct result for a certain input.  And then there are those who point out that this is not unit testing, but integration testing.  And then there is the realization that there is no such thing as unit testing, only integration testing.  But by now we have entered the realm of philosophy.

ContentLicense: CC BY-SA 3.0

Title: Junit testing for a function

Body:
I have a confusion regarding Junit testing.For some functions(add function) with closed business logic we can make unit testing by asserting the function.

For example

public int add(int a,int b){
  int c = a+b;
  return c;
}

But for some function(as below example) in a route what methodology we have to do.

For example

public int foo(int totalnum){
  Zoo soo = new Zoo();
  int giraffNumber = soo.giraffe(totalnum);//here we are calling another method
  return giraffNumber;
}

For these kind of methods what approach we have to do.Does we need to write another class.

Can anybody please advise me with an example.


问:
Java Fibonacci series
What would be the next step in order to ask the user which of the numbers in this series of 30 he wants to see and prompts for an integer input - a number between 1 and 30 (inclusive)?

So if the user wants to see the fifth (5th) number of the Fibonacci series the user would input the integer 5 in response to the prompt.

```<code>public class MyFibonacci {
    public static void main(String a[]) {
         int febCount = 30;
         int[] feb = new int[febCount];
         feb[0] = 0;
         feb[1] = 1;
         for(int i=2; i < febCount; i++) {
             feb[i] = feb[i-1] + feb[i-2];
         }

         for(int i=0; i< febCount; i++) {
                 System.out.print(feb[i] + " ");
         }
    }
}
</code>```

答:
```<code>public class Fibonacci_series  // upto less than a given number
{
    public static void main(long n)
    {
        long a=0, b=1, c=0;
        while (c<n)
        {
            a=b;
            b=c;
            System.out.print(c+", ");
            c=a+b;
        }
        System.out.print("....");
    }
}
</code>```

Title: Java Fibonacci series

Body:
What would be the next step in order to ask the user which of the numbers in this series of 30 he wants to see and prompts for an integer input - a number between 1 and 30 (inclusive)?

So if the user wants to see the fifth (5th) number of the Fibonacci series the user would input the integer 5 in response to the prompt.

public class MyFibonacci {
    public static void main(String a[]) {
         int febCount = 30;
         int[] feb = new int[febCount];
         feb[0] = 0;
         feb[1] = 1;
         for(int i=2; i < febCount; i++) {
             feb[i] = feb[i-1] + feb[i-2];
         }

         for(int i=0; i< febCount; i++) {
                 System.out.print(feb[i] + " ");
         }
    }
}


答:
Ideally you turn that local variable into a field of your class. Or, probably not a Zoo object, but a factory for Zoo objects.

This factor gets inserted via dependency injection. And now you can use a mocking framework such as Mockito to have the factory instance return a mocked Zoo object.

That is you gain control over such objects. The key thing is to not call new for business logic objects.

Title: Junit testing for a function


问:
SQL: order by calculated rate between two tables
I might be confusing syntax from other languages with SQL and that's why this isn't working, my subquery is definitely incorrect.

Having the following 2 tables:

```<code>TEST_RESULTS
Student_ID Test_ID Test_Result
    A1       234       90
    B2       234       80
    C3       345       85
    D4       234       95
    A1       345       95
    C3       456       95

TEST_DESCRIPTION
Test_ID  Test_Description Passing_Score
  234         Test A            85
  345         Test B            90
  456         Test C            95
</code>```

I want to calculate the rate of passing for each test and sort by it.

The output I am looking for:

```<code>Test_ID   Test_Description  students_taking students_passing   rate
456             Test C         1                1               1
234             Test A         3                2               0.666666667
345             Test B         2                1               0.5
</code>```

This is my query

```<code>SELECT td.Test_ID, td.Test_Description, COUNT(tr.Student_ID) as
students_taking, students_passing, students_passing/students_taking as rate
FROM
(SELECT td.Test_ID, td.Test_Description, COUNT(tr.Student_ID) as
students_passing
FROM TEST_RESULTS tr
JOIN TEST_DESCRIPTION td
on tr.Test_ID = td.Test_ID
WHERE tr.Test_Result > td.)
GROUP BY td.Test_ID, td.Test_Description
ORDER BY rate DESC, td.Test_ID, td.Test_Description
</code>```

My select from select is wrong, because I am getting no results for this query.

答:
I'm using CTE, LEFT JOIN for getting the desired result.
Try this query -- </p>

```<code>;WITH CTE
AS
(
    SELECT
        TD.TEST_ID,
        TEST_DESCRIPTION,
        COUNT(TR.STUDENT_ID) AS STUDENTS_TAKING,
        COUNT(CASE WHEN TR.TEST_RESULT >= TD.PASSING_SCORES THEN
            TR.STUDENT_ID END) AS STUDENTS_PASSING
    FROM TEST_DESCRIPTION TD
    LEFT JOIN TEST_RESULTS TR
    ON TD.TEST_ID = TR.TEST_ID
    GROUP BY TD.TEST_ID,
        TEST_DESCRIPTION
)
SELECT
    TEST_ID,
    TEST_DESCRIPTION,
    STUDENTS_TAKING,
    STUDENTS_PASSING,
    STUDENTS_PASSING / CONVERT (DECIMAL(4,2),STUDENTS_TAKING) AS RATE
FROM CTE
ORDER BY TEST_DESCRIPTION
</code>```

Body:
I might be confusing syntax from other languages with SQL and that's why this isn't working, my subquery is definitely incorrect.

Having the following 2 tables:

TEST_RESULTS
Student_ID Test_ID Test_Result
    A1       234       90
    B2       234       80
    C3       345       85
    D4       234       95
    A1       345       95
    C3       456       95

TEST_DESCRIPTION
Test_ID  Test_Description Passing_Score
  234         Test A            85
  345         Test B            90
  456         Test C            95

I want to calculate the rate of passing for each test and sort by it.

The output I am looking for:

Test_ID   Test_Description  students_taking students_passing   rate
456             Test C         1                1               1
234             Test A         3                2               0.666666667
345             Test B         2                1               0.5

This is my query

SELECT td.Test_ID, td.Test_Description, COUNT(tr.Student_ID) as
students_taking, students_passing, students_passing/students_taking as rate
FROM
(SELECT td.Test_ID, td.Test_Description, COUNT(tr.Student_ID) as
students_passing
FROM TEST_RESULTS tr
JOIN TEST_DESCRIPTION td
on tr.Test_ID = td.Test_ID
WHERE tr.Test_Result > td.)
GROUP BY td.Test_ID, td.Test_Description
ORDER BY rate DESC, td.Test_ID, td.Test_Description

My select from select is wrong, because I am getting no results for this query.

Body:
I'm using CTE, LEFT JOIN for getting the desired result.
Try this query --

;WITH CTE
AS
(
    SELECT
        TD.TEST_ID,
        TEST_DESCRIPTION,
        COUNT(TR.STUDENT_ID) AS STUDENTS_TAKING,
        COUNT(CASE WHEN TR.TEST_RESULT >= TD.PASSING_SCORES THEN
            TR.STUDENT_ID END) AS STUDENTS_PASSING
    FROM TEST_DESCRIPTION TD
    LEFT JOIN TEST_RESULTS TR
    ON TD.TEST_ID = TR.TEST_ID
    GROUP BY TD.TEST_ID,
        TEST_DESCRIPTION
)
SELECT
    TEST_ID,
    TEST_DESCRIPTION,
    STUDENTS_TAKING,
    STUDENTS_PASSING,
    STUDENTS_PASSING / CONVERT (DECIMAL(4,2),STUDENTS_TAKING) AS RATE
FROM CTE
ORDER BY TEST_DESCRIPTION


问:
Element.but selector CSS
I saw this code on one the sites I am studying.

```<code>.site-header .widget-area span.but
</code>```

I am still kind of new to the whole CSS thing but what exactly does the span.but part mean? Is it the same as the pseudo selector :not?

答: No, it's just a regular class selector matching the class "but". There are no class selectors that have special meanings like pseudo-classes do. Every class selector is a literal match for class names within the class attribute in HTML, or whatever represents a class name in the document language.</p>

Title: Element.but selector CSS

Body:
I saw this code on one the sites I am studying.

.site-header .widget-area span.but

I am still kind of new to the whole CSS thing but what exactly does the span.but part mean? Is it the same as the pseudo selector :not?


答:
It is the way of representing two class of same element to increase the weight.

for example

```<code><div class="menu nav">
  <div class="sub-menu">
  </div>
</div>
</code>```

In the above code .menu .sub-menu and .menu.nav .sub-menu will represent same element i.e. .sub-menu but .menu.nav .sub-menu has higher weight than .menu .sub-menu.

P.S. Higher weight means the one with high weight will apply first than rest.

Title: Element.but selector CSS

Body:
It is the way of representing two class of same element to increase the weight.

for example

<div class="menu nav">
  <div class="sub-menu">
  </div>
</div>

In the above code .menu .sub-menu and .menu.nav .sub-menu will represent same element i.e. .sub-menu but .menu.nav .sub-menu has higher weight than .menu .sub-menu.

P.S. Higher weight means the one with high weight will apply first than rest.


问:
best way for sorting some arrays
I have some array:

```<code>trade_prices[n]
trade_volumes[n]
trade_dates[n]
trade_tickers[n]
</code>```

and I want to sort them by tickers and then by dates.

how can I sort them?

答:
Seems like you should rethink the design. I think creating a class for these properties and having a collection of the class type is better:

```<code>class Trade
{
    double price;
    double volume;
    Date date;
    String tickers;
}
</code>```

Then for sorting implement the Comparator interface. An example, after you create the class could be: How to sort by two fields in Java?

Another option, as mentioned by saka1029, is to use Comparator's functions of Comparator.comparing and Comparator.thenComparing on the steam of the class's objects.

Title: best way for sorting some arrays

Body:
I have some array:

trade_prices[n]
trade_volumes[n]
trade_dates[n]
trade_tickers[n]

and I want to sort them by tickers and then by dates.

how can I sort them?

Body:
Seems like you should rethink the design. I think creating a class for these properties and having a collection of the class type is better:

class Trade
{
    double price;
    double volume;
    Date date;
    String tickers;
}

Then for sorting implement the Comparator interface. An example, after you create the class could be: How to sort by two fields in Java?

Another option, as mentioned by saka1029, is to use Comparator's functions of Comparator.comparing and Comparator.thenComparing on the steam of the class's objects.


问:
Error when trying to extract hyperledger artifacts
i am using Windows 10 (64-bit) and i seem to have all the prerequisites installed.

However, while running the command curl -sSL https://raw.githubusercontent.com/hyperledger/fabric/master/examples/e2e_cli/bootstrap.sh | bash on Git-Bash, i will get the following error:

```<code>$ curl -sSL https://raw.githubusercontent.com/hyperledger/fabric/master/examples/e2e_cli/bootstrap.sh | bash
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  1205    0  1205    0     0    976      0 --:--:--  0:00:01 --:--:--   988

gzip: stdin: not in gzip format
tar: Child returned status 1
tar: Error is not recoverable: exiting now
bash: line 12: cd: release/mingw32_nt-10.0-wow-i686: No such file or directory
sh: download-dockerimages.sh: No such file or directory
</code>```

答:
It does work on my Windows 10, with Git 2.13.

Try again, but with a simplify PATH first.

In a CMD, type:

```<code>set PATH=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\
set GH=C:\path\to\Git\2.13
set PATH=%GH%\bin;%GH%\usr\bin;%GH%\mingw64\bin;%PATH%
</code>```

Then type 'bash', and in the bash session, try your curl command again.

Body:
i am using Windows 10 (64-bit) and i seem to have all the prerequisites installed.

However, while running the command curl -sSL https://raw.githubusercontent.com/hyperledger/fabric/master/examples/e2e_cli/bootstrap.sh | bash on Git-Bash, i will get the following error:

$ curl -sSL https://raw.githubusercontent.com/hyperledger/fabric/master/examples/e2e_cli/bootstrap.sh | bash
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  1205    0  1205    0     0    976      0 --:--:--  0:00:01 --:--:--   988

gzip: stdin: not in gzip format
tar: Child returned status 1
tar: Error is not recoverable: exiting now
bash: line 12: cd: release/mingw32_nt-10.0-wow-i686: No such file or directory
sh: download-dockerimages.sh: No such file or directory

Body:
It does work on my Windows 10, with Git 2.13.

Try again, but with a simplify PATH first.

In a CMD, type:

set PATH=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\
set GH=C:\path\to\Git\2.13
set PATH=%GH%\bin;%GH%\usr\bin;%GH%\mingw64\bin;%PATH%

Then type 'bash', and in the bash session, try your curl command again.


问:
How can I get my javascript work in an asp.net cshtml file?
I have a html input for uploading a picture to my ftp, and I want my JS the detect changes on my button.
My cshtml is:

```<code>    @using (Html.BeginForm("UploadFile", "Upload", FormMethod.Post, new {
    enctype = "multipart/form-data" }))
    {

    <input id="uploadFile" placeholder="No file..." disabled="disabled" />
    <div class="fileUpload btn btn-primary">
        <span>Browse</span>
        <input id="uploadBtn" type="file" class="upload" />
    </div>
    <input type="submit" title="OK" />
}
</code>```

and my script is

```<code><head>
<script type="text/javascript" language="javascript">
        document.getElementById("uploadBtn").onchange = function ()
        {
            document.getElementById("uploadFile").value = this.value;
        };
    </script>
</head>
</code>```

When I run my code I get the following message:

0x800a138f - JavaScript runtime error: Unable to get property 'onchange' of undefined or null reference

I checked my html and JS in fiddle, everything works great, so I guess that Razor and JS have some problems with each others.
Any tips?

答:
Try this:

1.

```<code><head>
<script type="text/javascript" language="javascript">

$(document).ready(function(){
        document.getElementById("uploadBtn").onchange = function ()
        {
            document.getElementById("uploadFile").value = this.value;
        };
});
    </script>
</head>
</code>```

As per @StephenMuecke : Move your script to immediately before the closing  tag (as my view it's best way)

 .............. .............

```<code><script type="text/javascript" language="javascript">

$(document).ready(function(){
  $('#uploadBtn').on('change', function() {
   $("#uploadFile").val($(this).val());
 })
});   </script>
</code>```

3.If you use separate script (.js file) then try

```<code>     $(document).on('change','#uploadBtn' ,function() {
         $("#uploadFile").val($(this).val());
      });
</code>```

Body:
I have a html input for uploading a picture to my ftp, and I want my JS the detect changes on my button.
My cshtml is:

    @using (Html.BeginForm("UploadFile", "Upload", FormMethod.Post, new {
    enctype = "multipart/form-data" }))
    {

    <input id="uploadFile" placeholder="No file..." disabled="disabled" />

        Browse
        <input id="uploadBtn" type="file" class="upload" />

    <input type="submit" title="OK" />
}

and my script is

When I run my code I get the following message:

0x800a138f - JavaScript runtime error: Unable to get property 'onchange' of undefined or null reference

I checked my html and JS in fiddle, everything works great, so I guess that Razor and JS have some problems with each others.
Any tips?

Body:
Try this:

1.

<head>
<script type="text/javascript" language="javascript">

$(document).ready(function(){
        document.getElementById("uploadBtn").onchange = function ()
        {
            document.getElementById("uploadFile").value = this.value;
        };
});
    </script>
</head>

As per @StephenMuecke : Move your script to immediately before the closing </body> tag (as my view it's best way)

<body> .............. .............

<script type="text/javascript" language="javascript">

$(document).ready(function(){
  $('#uploadBtn').on('change', function() {
   $("#uploadFile").val($(this).val());
 })
});   </script>

</body>

3.If you use separate script (.js file) then try

     $(document).on('change','#uploadBtn' ,function() {
         $("#uploadFile").val($(this).val());
      });


问:
Verify whether the next char is the same as first char
I found a problem and i tried my logic but i failed to get to the solution.

This is the problem i am trying to solve in java.

For every opening brace (i.e., (, {, or [), there is a matching closing brace (i.e., ), }, or ]) of the same type (i.e., (matches ), { matches }, and [ matches ]). An opening brace must appear before (to the left of) it’s matching closing brace. For example, ]{}[ is not balanced.

No unmatched braces lie between some pair of matched braces. For example, ({[]}) is balanced, but {[}] and [{)] are not balanced.

I want to write java code which would take such a string input of braces and output whether it is balanced or not.

I am not able to apply logic for this kind of code, i tried however it was not even close to expectations. Please provide with some logic. I know this is not a homework completion site but i am stuck on the logic of this problem. a code snippet would be appreciated.

答:
Try this.

```<code>public static boolean isBalanced(String s) {
    Deque<Character> stack = new LinkedList<>();
    for (int i = 0; i < s.length(); ++i) {
        char c = s.charAt(i);
        switch (c) {
        case '(': stack.push(')'); break;
        case '[': stack.push(']'); break;
        case '{': stack.push('}'); break;
        case ')': case ']': case '}':
            if (stack.isEmpty() || !stack.pop().equals(c))
                return false;
            break;
        }
    }
    return stack.isEmpty();
}
</code>```

No switch version:

```<code>public static boolean isBalanced(String s) {
    Deque<Character> stack = new LinkedList<>();
    for (int i = 0; i < s.length(); ++i) {
        char c = s.charAt(i);
        if (c == '(')
            stack.push(')');
        else if (c == '[')
            stack.push(']');
        else if (c == '{')
            stack.push('}');
        else if (c == ')' || c == ']' || c == '}')
            if (stack.isEmpty() || !stack.pop().equals(c))
                return false;
    }
    return stack.isEmpty();
}
</code>```

Body:
Try this.

public static boolean isBalanced(String s) {
    Deque<Character> stack = new LinkedList<>();
    for (int i = 0; i < s.length(); ++i) {
        char c = s.charAt(i);
        switch (c) {
        case '(': stack.push(')'); break;
        case '[': stack.push(']'); break;
        case '{': stack.push('}'); break;
        case ')': case ']': case '}':
            if (stack.isEmpty() || !stack.pop().equals(c))
                return false;
            break;
        }
    }
    return stack.isEmpty();
}

No switch version:

public static boolean isBalanced(String s) {
    Deque<Character> stack = new LinkedList<>();
    for (int i = 0; i < s.length(); ++i) {
        char c = s.charAt(i);
        if (c == '(')
            stack.push(')');
        else if (c == '[')
            stack.push(']');
        else if (c == '{')
            stack.push('}');
        else if (c == ')' || c == ']' || c == '}')
            if (stack.isEmpty() || !stack.pop().equals(c))
                return false;
    }
    return stack.isEmpty();
}


问:
Zurb Foundation javascript reInit module not working
i'm ajaxifying a website. My menu should always be sticky (using the sticky module provided by Foundation). But it is only sticky on a regular page load, and not on ajax reload (aka when navigating on the website)
I'm trying to re-initialise the module when the event ajaxComplete happens, using the line provided in the documentation of Foundation 6:

```<code>$(document).ajaxComplete(function () {
    Foundation.reInit($('.sticky'));
    //other code
});
</code>```

But it doesn't seem to work, because I get this error in the console :

```<code>TypeError: Cannot read property '_init' of undefined
    at HTMLElement.<anonymous> (foundation.core.js:103)
    at Function.each (jquery.min.js?ver=2.1.0:2)
    at o.fn.init.each (jquery.min.js?ver=2.1.0:2)
    at Object.reInit (foundation.core.js:102)
    at HTMLDocument.<anonymous> (stickyfooter.js:28)
    at HTMLDocument.dispatch (jquery.min.js?ver=2.1.0:3)
    at HTMLDocument.r.handle (jquery.min.js?ver=2.1.0:3)
    at Object.trigger (jquery.min.js?ver=2.1.0:3)
    at x (jquery.min.js?ver=2.1.0:4)
    at XMLHttpRequest.<anonymous> (jquery.min.js?ver=2.1.0:4)
</code>```

Which I don't understand. What does it mean ? How can I make the module work after an ajax reload ?
The website in action : http://lesdeuxvagues.com/demo

答:
You didn't post your markup, but I visited the site and don't see a ".sticky" class in your CSS.  You are calling

```<code>    Foundation.reInit()
</code>```

on a jQuery selector.  So does

```<code>    $('.sticky')
</code>```

select anything on your page?  Why don't you try:

```<code>       Foundation.reInit($('[data-sticky]'))
</code>```

which would reinitialize all the elements with attribute data-sticky

Body:
i'm ajaxifying a website. My menu should always be sticky (using the sticky module provided by Foundation). But it is only sticky on a regular page load, and not on ajax reload (aka when navigating on the website)
I'm trying to re-initialise the module when the event ajaxComplete happens, using the line provided in the documentation of Foundation 6:

$(document).ajaxComplete(function () {
    Foundation.reInit($('.sticky'));
    //other code
});

But it doesn't seem to work, because I get this error in the console :

TypeError: Cannot read property '_init' of undefined
    at HTMLElement.<anonymous> (foundation.core.js:103)
    at Function.each (jquery.min.js?ver=2.1.0:2)
    at o.fn.init.each (jquery.min.js?ver=2.1.0:2)
    at Object.reInit (foundation.core.js:102)
    at HTMLDocument.<anonymous> (stickyfooter.js:28)
    at HTMLDocument.dispatch (jquery.min.js?ver=2.1.0:3)
    at HTMLDocument.r.handle (jquery.min.js?ver=2.1.0:3)
    at Object.trigger (jquery.min.js?ver=2.1.0:3)
    at x (jquery.min.js?ver=2.1.0:4)
    at XMLHttpRequest.<anonymous> (jquery.min.js?ver=2.1.0:4)

Which I don't understand. What does it mean ? How can I make the module work after an ajax reload ?
The website in action : http://lesdeuxvagues.com/demo

Body:
You didn't post your markup, but I visited the site and don't see a ".sticky" class in your CSS.  You are calling

    Foundation.reInit()

on a jQuery selector.  So does

    $('.sticky')

select anything on your page?  Why don't you try:

       Foundation.reInit($('[data-sticky]'))

which would reinitialize all the elements with attribute data-sticky


问:
Match near similar characters/words
I have the following dataframe with columns X and Y,

```<code>    X                                   Y
1   SAN DIEGO                           FOND DU LAC
2   THE RIO GRANDE                      RIO GRANDE
3   RIO GRANDE                          RIO GRANDE
4   WEST TENNESSEE                      TENNESSEE
5   EP De SAN JOAQUIN                   De SAN JOAQUIN
6   SOUTHERN VIRGINIA                   VIRGINIA
7   SOUTHERN VIRGINIA                   SOUTHWESTERN VIRGINIA
8   EN COLOMBIA                         COLOMBIA
9   THE EP De NORTHERN CALIFORNIA       De NORTHERN CALIFORNIA
10  FLORIDA                             NEW JERSY
</code>```

I want to get nonmatching rows, 1 and 10. Rows 2-9 are matches or close matches and are okay. My expected data frame is

```<code>    X                                   Y
1   SAN DIEGO                           FOND DU LAC
10  FLORIDA                             NEW JERSY
</code>```

答:
In R we split the string by space in each column, check whether there is any intersect between the words, find the lengths of the list and subset the dataset where the length is 0

```<code>df1[!lengths(Map(intersect, strsplit(df1$X, "\\s+"), strsplit(df1$Y, "\\s+"))),]
#          X           Y
#1  SAN DIEGO FOND DU LAC
#10   FLORIDA   NEW JERSY
</code>```

Instead of splitting by each column, we can also loop through the columns, do the split

```<code>df1[!lengths(do.call(Map, c(intersect, unname(lapply(df1, strsplit, split="\\s+"))))),]
#      X           Y
#1  SAN DIEGO FOND DU LAC
#10   FLORIDA   NEW JERSY
</code>```

Or another option is stringdist

```<code>library(stringdist)
i1 <- with(df1, stringdist(X, Y, method = "qgram"))
df1[i1 %in% tail(sort(i1), 2),]
#          X           Y
#1  SAN DIEGO FOND DU LAC
#10   FLORIDA   NEW JERSY
</code>```

Title: Match near similar characters/words

Body:
I have the following dataframe with columns X and Y,

    X                                   Y
1   SAN DIEGO                           FOND DU LAC
2   THE RIO GRANDE                      RIO GRANDE
3   RIO GRANDE                          RIO GRANDE
4   WEST TENNESSEE                      TENNESSEE
5   EP De SAN JOAQUIN                   De SAN JOAQUIN
6   SOUTHERN VIRGINIA                   VIRGINIA
7   SOUTHERN VIRGINIA                   SOUTHWESTERN VIRGINIA
8   EN COLOMBIA                         COLOMBIA
9   THE EP De NORTHERN CALIFORNIA       De NORTHERN CALIFORNIA
10  FLORIDA                             NEW JERSY

I want to get nonmatching rows, 1 and 10. Rows 2-9 are matches or close matches and are okay. My expected data frame is

    X                                   Y
1   SAN DIEGO                           FOND DU LAC
10  FLORIDA                             NEW JERSY

Body:
In R we split the string by space in each column, check whether there is any intersect between the words, find the lengths of the list and subset the dataset where the length is 0

df1[!lengths(Map(intersect, strsplit(df1$X, "\\s+"), strsplit(df1$Y, "\\s+"))),]
#          X           Y
#1  SAN DIEGO FOND DU LAC
#10   FLORIDA   NEW JERSY

Instead of splitting by each column, we can also loop through the columns, do the split

df1[!lengths(do.call(Map, c(intersect, unname(lapply(df1, strsplit, split="\\s+"))))),]
#      X           Y
#1  SAN DIEGO FOND DU LAC
#10   FLORIDA   NEW JERSY

Or another option is stringdist

library(stringdist)
i1 <- with(df1, stringdist(X, Y, method = "qgram"))
df1[i1 %in% tail(sort(i1), 2),]
#          X           Y
#1  SAN DIEGO FOND DU LAC
#10   FLORIDA   NEW JERSY


Title: How to calculate normals for an icosahedron?

Body:
I want to calculate the normals for an icosahedron with its origin at {0.0, 0.0, 0.0}, but I do not have any idea of how to do it!

For example, when i constructed a cube earlier, it was rather simple to get the normals, because each face of the cube was directed parallel either to the x, y or z-axis and the arrays containing the vertices and normals looked like that:

var vertices = [
  -1.0, -1.0,  1.0,    1.0, -1.0,  1.0,
   1.0,  1.0,  1.0,   -1.0,  1.0,  1.0,

  -1.0, -1.0, -1.0,   -1.0,  1.0, -1.0,
   1.0,  1.0, -1.0,    1.0, -1.0, -1.0,

  -1.0,  1.0, -1.0,   -1.0,  1.0,  1.0,
   1.0,  1.0,  1.0,    1.0,  1.0, -1.0,

  -1.0, -1.0, -1.0,    1.0, -1.0, -1.0,
   1.0, -1.0,  1.0,   -1.0, -1.0,  1.0,

   1.0, -1.0, -1.0,    1.0,  1.0, -1.0,
   1.0,  1.0,  1.0,    1.0, -1.0,  1.0,

  -1.0, -1.0, -1.0,   -1.0, -1.0,  1.0,
  -1.0,  1.0,  1.0,   -1.0,  1.0, -1.0
];

var normals = [
   0.0,  0.0,  1.0,    0.0,  0.0,  1.0,
   0.0,  0.0,  1.0,    0.0,  0.0,  1.0,

   0.0,  0.0, -1.0,    0.0,  0.0, -1.0,
   0.0,  0.0, -1.0,    0.0,  0.0, -1.0,

   0.0,  1.0,  0.0,    0.0,  1.0,  0.0,
   0.0,  1.0,  0.0,    0.0,  1.0,  0.0,

   0.0, -1.0,  0.0,    0.0, -1.0,  0.0,
   0.0, -1.0,  0.0,    0.0, -1.0,  0.0,

   1.0,  0.0,  0.0,    1.0,  0.0,  0.0,
   1.0,  0.0,  0.0,    1.0,  0.0,  0.0,

  -1.0,  0.0,  0.0,   -1.0,  0.0,  0.0,
  -1.0,  0.0,  0.0,   -1.0,  0.0,  0.0
];

But now, working on my icosahedron, things are getting a bit more complicated...

Edit 1:

Following the instructions of the answer given, i tried to calculate the normals this way:

First I stored the vertices in a multidimensional Array like that:

var r = (1 + Math.sqrt(5)) / 2;

var triangles = [

  [ [-1.0, r, 0.0],   [0.0, 1.0, r],      [1.0, r, 0.0] ],
  [ [1.0, r, 0.0],    [0.0, 1.0, -r],    [-1.0, r, 0.0] ],
  [ [1.0, r, 0.0],    [0.0, 1.0, r],      [r, 0.0, 1.0] ],
  [ [1.0, r, 0.0],    [r, 0.0, -1.0],    [0.0, 1.0, -r] ],
  [ [r, 0.0, -1.0],   [1.0, r, 0.0],      [r, 0.0, 1.0] ],
  [ [-1.0, -r, 0.0],  [1.0, -r, 0.0],    [0.0, -1.0, r] ],
  [ [-1.0, -r, 0.0],  [0.0, -1.0, -r],   [1.0, -r, 0.0] ],
  [ [-1.0, -r, 0.0],  [0.0, -1.0, r],    [-r, 0.0, 1.0] ],
  [ [-1.0, -r, 0.0],  [-r, 0.0, -1.0],  [0.0, -1.0, -r] ],
  [ [-r, 0.0, 1.0],   [-r, 0.0, -1.0],  [-1.0, -r, 0.0] ],
  [ [-1.0, r, 0.0],   [-r, 0.0, 1.0],     [0.0, 1.0, r] ],
  [ [-1.0, r, 0.0],   [0.0, 1.0, -r],   [-r, 0.0, -1.0] ],
  [ [-1.0, r, 0.0],   [-r, 0.0, -1.0],   [-r, 0.0, 1.0] ],
  [ [1.0, -r, 0.0],   [r, 0.0, 1.0],     [0.0, -1.0, r] ],
  [ [1.0, -r, 0.0],   [0.0, -1.0, -r],   [r, 0.0, -1.0] ],
  [ [1.0, -r, 0.0],   [r, 0.0, -1.0],     [r, 0.0, 1.0] ],
  [ [0.0, -1.0, -r],  [-r, 0.0, -1.0],   [0.0, 1.0, -r] ],
  [ [0.0, -1.0, -r],  [0.0, 1.0, -r],    [r, 0.0, -1.0] ],
  [ [0.0, 1.0, r],    [-r, 0.0, 1.0],    [0.0, -1.0, r] ],
  [ [0.0, 1.0, r],    [0.0, -1.0, r],     [r, 0.0, 1.0] ]

];

Then, based on the given answer, I wrote this function to calculate the normals...

var normals = [ ];

triangles.forEach(function (triangle) {
  var v1 = triangle[0],
      v2 = triangle[1],
      v3 = triangle[2];
  var p12 = new Array(3);
  p12[0] = v2[0] - v1[0];
  p12[1] = v2[1] - v1[1];
  p12[2] = v2[2] - v1[2];
  var p23 = new Array(3);
  p23[0] = v3[0] - v2[0];
  p23[1] = v3[1] - v2[1];
  p23[2] = v3[2] - v2[2];
  var cp = new Array(3);
  var x1 = p12[0],
      y1 = p12[1],
      z1 = p12[2];
  var x2 = p23[0],
      y2 = p23[1],
      z2 = p23[2];
  cp[0] = y1 * z2 - z1 * y2;
  cp[1] = z1 * x2 - x1 * z2;
  cp[2] = x1 * y2 - y1 * x2;
  var x = Math.pow(cp[0], 2),
      y = Math.pow(cp[1], 2),
      z = Math.pow(cp[2], 2);
  var len = Math.sqrt(x + y + z);
  var normal = new Array(3);
  normal[0] = cp[0] / len;
  normal[1] = cp[1] / len;
  normal[2] = cp[2] / len;
  for (var i = 0; i < 3; i++) {
    normals.push(normal);
  }
});

...to finally unpack and use them:

var unpackedNormals = [ ];

for (var n in normals) {
  unpackedNormals = unpackedNormals.concat(normals[n]);
}

var vertexNormalData = unpackedNormals;

But somehow it doesn't work like it should!

I can see the icosahedron on screen, but the lighting of the triangles on the surface seems to be completly wrong.

I ran the same program with my earlier mentioned cube-function instead of the one constructing the icosahedron, and it all works perfectly fine, so I think the error must be located within this new function to calculate the normals.

Maybe someone has an idea what I did wrong?

I'd be thankful for any help!

PS: Please excuse my bad english.

Edit 2: PROBLEM SOLVED!

I changed the order of the vectors in the triangle-array and now all of the triangles behave like they should!

I updated the triangle-array in this post too, so the snipped further up now represents the correct order, AFAIK.

Body:
If you are interested in the results only, here below is a Wavefront icosahedron.obj file I exported from Blender with triangulated vertices, textures and normals.

# Blender v2.77 (sub 0) OBJ File: 'icosahedron.blend'
# www.blender.org
mtllib icosahedron.mtl
o Icosphere
v 0.000000 -1.000000 0.000000
v 0.723600 -0.447215 0.525720
v -0.276385 -0.447215 0.850640
v -0.894425 -0.447215 0.000000
v -0.276385 -0.447215 -0.850640
v 0.723600 -0.447215 -0.525720
v 0.276385 0.447215 0.850640
v -0.723600 0.447215 0.525720
v -0.723600 0.447215 -0.525720
v 0.276385 0.447215 -0.850640
v 0.894425 0.447215 0.000000
v 0.000000 1.000000 0.000000
vt 0.6739 0.5441
vt 0.5057 0.4329
vt 0.6731 0.1917
vt 0.5162 0.7848
vt 0.8418 0.4311
vt 0.8321 0.7831
vt 0.3418 0.5689
vt 0.3321 0.2169
vt 1.0162 0.2152
vt 1.0057 0.5671
vt 1.1731 0.8083
vt 0.1731 0.8083
vt 0.1739 0.4559
vt 0.0162 0.2152
vt 0.0057 0.5671
vn 0.1876 -0.7947 0.5774
vn 0.6071 -0.7947 0.0000
vn -0.4911 -0.7947 0.3568
vn -0.4911 -0.7947 -0.3568
vn 0.1876 -0.7947 -0.5774
vn 0.9822 -0.1876 0.0000
vn 0.3035 -0.1876 0.9342
vn -0.7946 -0.1876 0.5774
vn -0.7946 -0.1876 -0.5774
vn 0.3035 -0.1876 -0.9342
vn 0.7946 0.1876 0.5774
vn -0.3035 0.1876 0.9342
vn -0.9822 0.1876 0.0000
vn -0.3035 0.1876 -0.9342
vn 0.7946 0.1876 -0.5774
vn 0.4911 0.7947 0.3568
vn -0.1876 0.7947 0.5774
vn -0.6071 0.7947 0.0000
vn -0.1876 0.7947 -0.5774
vn 0.4911 0.7947 -0.3568
usemtl None
s off
f 1/1/1 2/2/1 3/3/1
f 2/2/2 1/1/2 6/4/2
f 1/1/3 3/3/3 4/5/3
f 1/1/4 4/5/4 5/6/4
f 1/1/5 5/6/5 6/4/5
f 2/2/6 6/4/6 11/7/6
f 3/3/7 2/2/7 7/8/7
f 4/5/8 3/3/8 8/9/8
f 5/6/9 4/5/9 9/10/9
f 6/4/10 5/6/10 10/11/10
f 2/2/11 11/7/11 7/8/11
f 3/3/12 7/8/12 8/9/12
f 4/5/13 8/9/13 9/10/13
f 5/6/14 9/10/14 10/11/14
f 6/4/15 10/12/15 11/7/15
f 7/8/16 11/7/16 12/13/16
f 8/14/17 7/8/17 12/13/17
f 9/15/18 8/14/18 12/13/18
f 10/12/19 9/15/19 12/13/19
f 11/7/20 10/12/20 12/13/20


问:
Why this code was not return at label in Kotlin
Why this code does not return from ints2.forEach but will output level 1 xx ==== every time?
And there is not difference when I set the label let@ to ints2.forEach.

```<code>fun foo() {
    val ints = Array(5, {i->i})
    ints.forEach let@ {
        println("level 1 $it ====")
        val ints2 = Array(3, {i->i})
        ints2.forEach {
            if (it == 2) return@let
            println("level 2 $it")
        }
    }
}

fun main(args: Array<String>) {
    foo()
}
</code>```

答:
Why this code does not return from ints.forEach and will output "level 1 xx ====" many times?

By returning to a label (@let in your case), it returns only from the lambda expression inside forEach. Therefore your foo() is equivalent to below code (using anonymous function instead of labels). That's why forEach block will still be executed for each value in the array. You can find more details here.

```<code>fun foo() {
    val ints = Array(5, {i->i})
    ints.forEach(fun(it: Int) {
        println("level 1 $it ====")
        val ints2 = Array(3, {i->i})
        ints2.forEach {
            if (it == 2) return
            println("level 2 $it")
        }
    })
}
</code>```

And there is not difference when I set the label "let@" to
  ints2.forEach.

Same reason as above. By settng @let label to ints2.forEach, this inner forEach block is still executed twice before it == 2.

Body:
Why this code does not return from ints2.forEach but will output level 1 xx ==== every time?
And there is not difference when I set the label let@ to ints2.forEach.

fun foo() {
    val ints = Array(5, {i->i})
    ints.forEach let@ {
        println("level 1 $it ====")
        val ints2 = Array(3, {i->i})
        ints2.forEach {
            if (it == 2) return@let
            println("level 2 $it")
        }
    }
}

fun main(args: Array<String>) {
    foo()
}

Body:
Why this code does not return from ints.forEach and will output "level 1 xx ====" many times?

By returning to a label (@let in your case), it returns only from the lambda expression inside forEach. Therefore your foo() is equivalent to below code (using anonymous function instead of labels). That's why forEach block will still be executed for each value in the array. You can find more details here.

fun foo() {
    val ints = Array(5, {i->i})
    ints.forEach(fun(it: Int) {
        println("level 1 $it ====")
        val ints2 = Array(3, {i->i})
        ints2.forEach {
            if (it == 2) return
            println("level 2 $it")
        }
    })
}

And there is not difference when I set the label "let@" to
  ints2.forEach.

Same reason as above. By settng @let label to ints2.forEach, this inner forEach block is still executed twice before it == 2.


问:
Java/JMS - Processing number of messages with handling failure scenarios
I have a requirement where I have to process number of messages. These messages will be inserted into a DB table by another process. All I have to do is to check for new messages in DB and send it to corresponding customer either email or http, depending on their configuration. The number of messages could be several thousands at any given time and the number of customers are around 1000.

I am planning to design this the way producer consumer works. Like producer thread polls DB for new messages and puts them into Queue and worker threads read these messages and processes.

At first it looked like JMS is the right solution for this requirement. But am seeking if any better alternatively like ExecutorService, using Threadpool suitable for this requirement given the following scenarios.

if one message delivery fails, I will have to retry it several times at least for 24 hours.

if one message delivery fails for a customer, all chances that other message delivery will also fail. So, I should try to send the first message before I process next message for that customer.

That means if I have one queue for all messages for all customers, then if one message fails, others will not be processed.

Can someone give me suggestion on how best I can handle this?

Thanks in advance.

答:
You should take a serious look at Apache Camel. It handles all of the threading, producing & consuming for you with a large number of built in components (SQL, JMS, SMTP, HTTP, File, etc) and your terminology around Consumers/Producers matches the Camel view of integration.

Implementing something like you describe is as easy as:

```<code>from("sql:select * from table")
  .to("jms:myQueue");
</code>```

Have a look at the list of endpoints

ContentLicense: CC BY-SA 2.5

Body:
You should take a serious look at Apache Camel. It handles all of the threading, producing & consuming for you with a large number of built in components (SQL, JMS, SMTP, HTTP, File, etc) and your terminology around Consumers/Producers matches the Camel view of integration.

Implementing something like you describe is as easy as:

from("sql:select * from table")
  .to("jms:myQueue");

Have a look at the list of endpoints


问:
PHP array to JavaScript array using json_encode()
How do I pass an array from PHP to the JavaScript function console.log()? I'm simulating a DB. I understand that I don't have an array declared in the code. I've tried using the .getJSON() function but it didn't work. Should I do an AJAX call for each element? I was thinking about that but there has to be a better way.

JavaScript code:

```<code>$.ajax({
         method:"POST",
         url:'php.php',
         data:"",
         dataType:'json',
         success:function(data){
             var y1=data;
             console.log(data.name);
         }
      });
</code>```

PHP code:

```<code><?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

if($_SERVER["REQUEST_METHOD"] == "POST")
{
    //assign vars after formatting to avoid a wrong login with correct
    //username and password
    $username = trim($_POST["user"]);

   $customer_array = array();

    $customer1 = array(
        'name' => '3',
        'city' => 'Houston'
    );

    $customer_array[] = $customer1;

    $customer2 = array(
        'name' => '2',
        'city' => 'Boston'
    );

    $customer_array[] = $customer2;

    $customer3 = array(
        'name' => "1",
        'city' => "Bossier City"
    );

    echo json_encode($customer_array);
}
</code>```

答:
I am just going to summarize my comments into an answer, first I would just turn off the json return for trouble shooting. You can parse the json after fact anyway:

```<code>$.ajax({
    // Do "type" here
    type:"POST",
    url:'php.php',
    // Send something to check in the script
    // This is optional, but I like to do it...
    data: {
        "action":"get_name_city"
    },
    success:function(data){
        // Do a try, just incase your parse fails
        try {
            // Parse the json here
            var getJson = JSON.parse(data);
            console.log(getJson);
            console.log(data);
        }
        catch(Exception) {
            // Show any errors that might get thrown
            console.log(Exception.message);
        }
    }
});
</code>```

PHP:

```<code># Check the action is set and is named
if(isset($_POST["action"]) && $_POST["action"] == "get_name_city") {
    $username = trim($_POST["user"]);
    $customer_array = array();

    $customer1 = array(
        'name' => '3',
        'city' => 'Houston'
    );

    $customer2 = array(
        'name' => '2',
        'city' => 'Boston'
    );

    $customer3 = array(
        'name' => "1",
        'city' => "Bossier City"
    );

    $customer_array[] = $customer1;
    $customer_array[] = $customer2;
    $customer_array[] = $customer3;

    # Just die here
    die(json_encode($customer_array));
}
# Die with error so there is some feedback to your ajax
die(json_encode(array('error'=>'No data was sent.')));
</code>```

Body:
How do I pass an array from PHP to the JavaScript function console.log()? I'm simulating a DB. I understand that I don't have an array declared in the code. I've tried using the .getJSON() function but it didn't work. Should I do an AJAX call for each element? I was thinking about that but there has to be a better way.

JavaScript code:

$.ajax({
         method:"POST",
         url:'php.php',
         data:"",
         dataType:'json',
         success:function(data){
             var y1=data;
             console.log(data.name);
         }
      });

PHP code:

<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

if($_SERVER["REQUEST_METHOD"] == "POST")
{
    //assign vars after formatting to avoid a wrong login with correct
    //username and password
    $username = trim($_POST["user"]);

   $customer_array = array();

    $customer1 = array(
        'name' => '3',
        'city' => 'Houston'
    );

    $customer_array[] = $customer1;

    $customer2 = array(
        'name' => '2',
        'city' => 'Boston'
    );

    $customer_array[] = $customer2;

    $customer3 = array(
        'name' => "1",
        'city' => "Bossier City"
    );

    echo json_encode($customer_array);
}

Body:
I am just going to summarize my comments into an answer, first I would just turn off the json return for trouble shooting. You can parse the json after fact anyway:

$.ajax({
    // Do "type" here
    type:"POST",
    url:'php.php',
    // Send something to check in the script
    // This is optional, but I like to do it...
    data: {
        "action":"get_name_city"
    },
    success:function(data){
        // Do a try, just incase your parse fails
        try {
            // Parse the json here
            var getJson = JSON.parse(data);
            console.log(getJson);
            console.log(data);
        }
        catch(Exception) {
            // Show any errors that might get thrown
            console.log(Exception.message);
        }
    }
});

PHP:

# Check the action is set and is named
if(isset($_POST["action"]) && $_POST["action"] == "get_name_city") {
    $username = trim($_POST["user"]);
    $customer_array = array();

    $customer1 = array(
        'name' => '3',
        'city' => 'Houston'
    );

    $customer2 = array(
        'name' => '2',
        'city' => 'Boston'
    );

    $customer3 = array(
        'name' => "1",
        'city' => "Bossier City"
    );

    $customer_array[] = $customer1;
    $customer_array[] = $customer2;
    $customer_array[] = $customer3;

    # Just die here
    die(json_encode($customer_array));
}
# Die with error so there is some feedback to your ajax
die(json_encode(array('error'=>'No data was sent.')));


问:
How to infer template parameters from constructors?
How to infer template parameters from constructors???

```<code>template<class $sign, signed $size>
class Integer;

template<>
class Integer<signed, 8>
{
public:
    typedef signed long long type;
};

typedef Integer<signed, 8>::type Int64;

template<class $sign, signed $size>
class Integer
{
public:
    Integer(Integer<$sign, $size>::type a){}
    // 1LL(Int64) => Integer<$sign, $size>::type => $sign, $size
    //How to infer <$ sign, $ size>
};

int main() {
    Integer a(1LL);
    return 0;
}
</code>```

How to infer template parameters from constructors???

1LL(Int64) => Integer<$sign, $size>::type => $sign, $size

How to infer <$ sign, $ size>

答:
http://en.cppreference.com/w/cpp/language/class_template_deduction as you can see this feature is available only starting C++17.  Although you might have to add another layer of indirection via a traits class or an explicit deduction guide to get your example to work.

If you have a compiler that supports -std=c++1z or -std=gnu++1z then you can use that as well.

Here is a working example https://wandbox.org/permlink/HqmitAQxSziZx8IC (the same code is pasted below also)

```<code>#include <iostream>

using std::cout;
using std::endl;

template <typename IntegerType, int width>
class Integer {
public:
    Integer(IntegerType) {
        cout << __PRETTY_FUNCTION__ << endl;
    }
};

template <>
class Integer<signed, 8> {
public:
    Integer(signed) {
        cout << __PRETTY_FUNCTION__ << endl;
    }
};

template <typename IntegerType>
Integer(IntegerType) -> Integer<IntegerType, sizeof(IntegerType)>;

int main() {
    Integer{1LL};
    return 0;
}
</code>```

Body:
How to infer template parameters from constructors???

template<class $sign, signed $size>
class Integer;

template<>
class Integer<signed, 8>
{
public:
    typedef signed long long type;
};

typedef Integer<signed, 8>::type Int64;

template<class $sign, signed $size>
class Integer
{
public:
    Integer(Integer<$sign, $size>::type a){}
    // 1LL(Int64) => Integer<$sign, $size>::type => $sign, $size
    //How to infer <$ sign, $ size>
};

int main() {
    Integer a(1LL);
    return 0;
}

How to infer template parameters from constructors???

1LL(Int64) => Integer<$sign, $size>::type => $sign, $size

How to infer <$ sign, $ size>

Body:
http://en.cppreference.com/w/cpp/language/class_template_deduction as you can see this feature is available only starting C++17.  Although you might have to add another layer of indirection via a traits class or an explicit deduction guide to get your example to work.

If you have a compiler that supports -std=c++1z or -std=gnu++1z then you can use that as well.

Here is a working example https://wandbox.org/permlink/HqmitAQxSziZx8IC (the same code is pasted below also)

#include <iostream>

using std::cout;
using std::endl;

template <typename IntegerType, int width>
class Integer {
public:
    Integer(IntegerType) {
        cout << __PRETTY_FUNCTION__ << endl;
    }
};

template <>
class Integer<signed, 8> {
public:
    Integer(signed) {
        cout << __PRETTY_FUNCTION__ << endl;
    }
};

template <typename IntegerType>
Integer(IntegerType) -> Integer<IntegerType, sizeof(IntegerType)>;

int main() {
    Integer{1LL};
    return 0;
}


问:
Get media elements from RSS using SyndicationFeed
I'm attempting to parse an RSS feed using C# and the SyndicationFeed class. I'm iterating over the items to get a list of SyndicationItems and that is exposing most of the feed properties, but what I cannot get out is the media:thumbnail element:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd"
    xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule"
    xmlns:media="http://search.yahoo.com/mrss/"
    xmlns:atom="http://www.w3.org/2005/Atom"
    xmlns:ddn="http://discoverydn.com/about">
  <channel>
    <title>Revision3 Feed</title>
    <link>http://revision3.com/user/1564421</link>
    <description>Customized RSS Feed of all your favorite Revision3 shows.</description>
    <language>en-us</language>
    <itunes:explicit>no</itunes:explicit>
    <itunes:summary></itunes:summary>
    <itunes:subtitle></itunes:subtitle>
    <itunes:author>Revision3</itunes:author>
    <itunes:owner>
      <itunes:email>feedback@revision3.com</itunes:email>
      <itunes:name>Revision3</itunes:name>
    </itunes:owner>
    <itunes:image href="http://revision3.com/forum/image.php?u=415677" />
    <itunes:keywords />
    <image>
      <title>Revision3 Feed</title>
      <width>100</width>
      <height>100</height>
      <link>http://revision3.com/user/1564221</link>
      <url>http://revision3.com/forum/image.php?u=415677</url>
    </image>
    <atom:link rel="self" type="application/rss+xml" title="Revision3 Feed" href="http://revision3.com/feed/user/0a7ehtg09b0ab0/" />
    <item>
      <title>Tekzilla Bites - Toyota Announces New Zero-Emission Fuel Cell Vehicle For 2015!</title>
      <link>http://revision3.com/tekzillabites/toyota-fuel-cell</link>
      <description>
<p>This year at their 2014 CES press conference, Toyota announced the Fuel Cell Vehicle (FCV): a hydrogen-powered vehicle whose only emission is water vapor going to market in 2015. Join Patrick for a look at the car, plus some of Toyota's announced specs, right from the CES show floor.
</p>
      </description>
      <content:encoded>
<p>This year at their 2014 CES press conference, Toyota announced the Fuel Cell Vehicle (FCV): a hydrogen-powered vehicle whose only emission is water vapor going to market in 2015. Join Patrick for a look at the car, plus some of Toyota's announced specs, right from the CES show floor.
</p>
      </content:encoded>
      <author>feedback@revision3.com (Revision3)</author>
      <pubDate>Tue, 07 Jan 2014 07:00:00 GMT</pubDate>
      <itunes:image href="http://revision3.com/forum/image.php?u=415677" />
      <itunes:duration>154</itunes:duration>
      <itunes:explicit>no</itunes:explicit>
      <itunes:keywords>toyota, fuel cell vehicle, hydrogen electric, hydrogen electricity, fcv, fuel cell, water exhaust, electric car, ces 2014</itunes:keywords>
      <itunes:author>Revision3</itunes:author>
      <itunes:subtitle>
This year at their 2014 CES press conference, Toyota announced the Fuel Cell Vehicle (FCV): a hydrogen-powered vehicle whose only emission is water vapor going to market in 2015. Join Patrick for a look at the car, plus some of Toyota's announced specs,
      </itunes:subtitle>
      <guid isPermaLink="false">/tekzilla/tekzillabites/0025/tekzilla--tekzillabites--0025--toyota-fuel-cell--hd720p30.h264.mp4</guid>
      <enclosure url="http://videos.revision3.com/revision3/web/tekzilla/tekzillabites/0025/tekzilla--tekzillabites--0025--toyota-fuel-cell--hd720p30.h264.mp4" length="27874999" type="video/mp4" />
      <media:content duration="154" medium="video" fileSize="27874999" url="http://videos.revision3.com/revision3/web/tekzilla/tekzillabites/0025/tekzilla--tekzillabites--0025--toyota-fuel-cell--hd720p30.h264.mp4" type="video/mp4">
        <media:title>Tekzilla Bites - Toyota Announces New Zero-Emission Fuel Cell Vehicle For 2015!</media:title>
        <media:description>
<p>This year at their 2014 CES press conference, Toyota announced the Fuel Cell Vehicle (FCV): a hydrogen-powered vehicle whose only emission is water vapor going to market in 2015. Join Patrick for a look at the car, plus some of Toyota's announced specs, right from the CES show floor.
</p>
        </media:description>
        <media:thumbnail url="http://videos.revision3.com/revision3/images/shows/tekzilla/tekzillabites/0025/tekzilla--tekzillabites--0025--toyota-fuel-cell--marge.thumb.jpg" width="640" height="360" />
        <media:thumbnail url="http://videos.revision3.com/revision3/images/shows/tekzilla/tekzillabites/0025/tekzilla--tekzillabites--0025--toyota-fuel-cell--medium.thumb.jpg" width="300" height="169" />
        <media:thumbnail url="http://videos.revision3.com/revision3/images/shows/tekzilla/tekzillabites/0025/tekzilla--tekzillabites--0025--toyota-fuel-cell--mini.thumb.jpg" width="100" height="100" />
        <media:player url="http://revision3.com/tekzillabites/toyota-fuel-cell" />
        <media:rating>nonadult</media:rating>
        <media:keywords>toyota, fuel cell vehicle, hydrogen electric, hydrogen electricity, fcv, fuel cell, water exhaust, electric car, ces 2014</media:keywords>
      </media:content>
      <ddn:id>28583</ddn:id>
    </item>
    <item>
      <title>Film Riot - Mondays: Getting Recognized, Poster Credits & Royalty Free Music!</title>
      <link>http://revision3.com/filmriot/poster-credits</link>
      <description>
Ryan opens up the mail sack and answers some questions!
      </description>
      <content:encoded>
Ryan opens up the mail sack and answers some questions!
      </content:encoded>
      <author>feedback@revision3.com (Revision3)</author>
      <pubDate>Tue, 07 Jan 2014 05:00:00 GMT</pubDate>
      <itunes:image href="http://revision3.com/forum/image.php?u=415677" />
      <itunes:duration>522</itunes:duration>
      <itunes:explicit>no</itunes:explicit>
      <itunes:keywords>getting recognized, getting yourself out there, poster credits, royalty free music, music, getting permission to use music, film riot, mail sack, questions, answers, q&a, ryan connolly</itunes:keywords>
      <itunes:author>Revision3</itunes:author>
      <itunes:subtitle>
Ryan opens up the mail sack and answers some questions!
      </itunes:subtitle>
      <guid isPermaLink="false">/filmriot/0364/filmriot--0364--poster-credits--hd720p30.h264.mp4</guid>
      <enclosure url="http://videos.revision3.com/revision3/web/filmriot/0364/filmriot--0364--poster-credits--hd720p30.h264.mp4" length="73676325" type="video/mp4" />
      <media:content duration="522" medium="video" fileSize="73676325" url="http://videos.revision3.com/revision3/web/filmriot/0364/filmriot--0364--poster-credits--hd720p30.h264.mp4" type="video/mp4">
        <media:title>Film Riot - Mondays: Getting Recognized, Poster Credits & Royalty Free Music!</media:title>
        <media:description>
Ryan opens up the mail sack and answers some questions!
        </media:description>
        <media:thumbnail url="http://videos.revision3.com/revision3/images/shows/filmriot/0364/filmriot--0364--poster-credits--marge.thumb.jpg" width="640" height="360" />
        <media:thumbnail url="http://videos.revision3.com/revision3/images/shows/filmriot/0364/filmriot--0364--poster-credits--medium.thumb.jpg" width="300" height="169" />
        <media:thumbnail url="http://videos.revision3.com/revision3/images/shows/filmriot/0364/filmriot--0364--poster-credits--mini.thumb.jpg" width="100" height="100" />
        <media:player url="http://revision3.com/filmriot/poster-credits" />
        <media:rating>nonadult</media:rating>
        <media:keywords>getting recognized, getting yourself out there, poster credits, royalty free music, music, getting permission to use music, film riot, mail sack, questions, answers, q&a, ryan connolly</media:keywords>
      </media:content>
      <ddn:id>28579</ddn:id>
    </item>
    <item>
      <title>Tekzilla Bites - Roku's Smart TV, More Channels, No Box- CES 2014</title>
      <link>http://revision3.com/tekzillabites/roku-tv-ces-2014</link>
      <description>
<p>Roku known for their ever popular line up of stand-alone media streaming devices, shook things up at CES 2014 this year. Enter: Roku TV, a TV with the Roku platform baked in and a few new extras that will surprise even veteran Roku users. Patrick Norton has the details. </p>
      </description>
      <content:encoded>
<p>Roku known for their ever popular line up of stand-alone media streaming devices, shook things up at CES 2014 this year. Enter: Roku TV, a TV with the Roku platform baked in and a few new extras that will surprise even veteran Roku users. Patrick Norton has the details. </p>
      </content:encoded>
      <author>feedback@revision3.com (Revision3)</author>
      <pubDate>Tue, 07 Jan 2014 05:00:00 GMT</pubDate>
      <itunes:image href="http://revision3.com/forum/image.php?u=415677" />
      <itunes:duration>105</itunes:duration>
      <itunes:explicit>no</itunes:explicit>
      <itunes:keywords>roku tv, roku, tcl, hisense, ces2014, ces 2014, roku lt, ruku 1, streaming, stream, media, tekzilla, roku remote, set top box, coard cutting</itunes:keywords>
      <itunes:author>Revision3</itunes:author>
      <itunes:subtitle>
Roku known for their ever popular line up of stand-alone media streaming devices, shook things up at CES 2014 this year. Enter: Roku TV, a TV with the Roku platform baked in and a few new extras that will surprise even veteran Roku users. Patrick Norton
      </itunes:subtitle>
      <guid isPermaLink="false">/tekzilla/tekzillabites/0024/tekzilla--tekzillabites--0024--roku-tv-ces-2014--hd720p30.h264.mp4</guid>
      <enclosure url="http://videos.revision3.com/revision3/web/tekzilla/tekzillabites/0024/tekzilla--tekzillabites--0024--roku-tv-ces-2014--hd720p30.h264.mp4" length="21262105" type="video/mp4" />
      <media:content duration="105" medium="video" fileSize="21262105" url="http://videos.revision3.com/revision3/web/tekzilla/tekzillabites/0024/tekzilla--tekzillabites--0024--roku-tv-ces-2014--hd720p30.h264.mp4" type="video/mp4">
        <media:title>Tekzilla Bites - Roku's Smart TV, More Channels, No Box- CES 2014</media:title>
        <media:description>
<p>Roku known for their ever popular line up of stand-alone media streaming devices, shook things up at CES 2014 this year. Enter: Roku TV, a TV with the Roku platform baked in and a few new extras that will surprise even veteran Roku users. Patrick Norton has the details. </p>
        </media:description>
        <media:thumbnail url="http://videos.revision3.com/revision3/images/shows/tekzilla/tekzillabites/0024/tekzilla--tekzillabites--0024--roku-tv-ces-2014--marge.thumb.jpg" width="640" height="360" />
        <media:thumbnail url="http://videos.revision3.com/revision3/images/shows/tekzilla/tekzillabites/0024/tekzilla--tekzillabites--0024--roku-tv-ces-2014--medium.thumb.jpg" width="300" height="169" />
        <media:thumbnail url="http://videos.revision3.com/revision3/images/shows/tekzilla/tekzillabites/0024/tekzilla--tekzillabites--0024--roku-tv-ces-2014--mini.thumb.jpg" width="100" height="100" />
        <media:player url="http://revision3.com/tekzillabites/roku-tv-ces-2014" />
        <media:rating>nonadult</media:rating>
        <media:keywords>roku tv, roku, tcl, hisense, ces2014, ces 2014, roku lt, ruku 1, streaming, stream, media, tekzilla, roku remote, set top box, coard cutting</media:keywords>
      </media:content>
      <ddn:id>28582</ddn:id>
    </item>
  </channel>
</rss>
</code>```

The entire media:content block is not deserialized from the XML passed in.
I've iterated over the entire element extensions block using

```<code>foreach (SyndicationElementExtension extension in item.ElementExtensions)
</code>```

but its not in there.
Is there any way I can tell the SyndicationFeed.Load() method to also parse this block for me:

```<code>SyndicationFeed feed = SyndicationFeed.Load(xmlReader);
</code>```

答:
I added an extension method for the SyndicationItem class.  Just create a class called 'ExtensionMethods.cs' in the root of your project and use the code below.  Be sure to change the namespace to match that of your project.</p>

```<code>using System;

namespace RFAnnouncer
{
    public static class ExtensionMethods
    {
        public static string GetEnclosureUri(this System.ServiceModel.Syndication.SyndicationItem item)
        {
            for (int i = 0; i < item.Links.Count; i++)
            {
                if (item.Links[i].RelationshipType == "enclosure")
                {
                    return item.Links[i].Uri.AbsoluteUri;
                }
            }
            return "";
        }
    }
}
</code>```

Body:
I'm attempting to parse an RSS feed using C# and the SyndicationFeed class. I'm iterating over the items to get a list of SyndicationItems and that is exposing most of the feed properties, but what I cannot get out is the media:thumbnail element:

    <?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd"
    xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule"
    xmlns:media="http://search.yahoo.com/mrss/"
    xmlns:atom="http://www.w3.org/2005/Atom"
    xmlns:ddn="http://discoverydn.com/about">
  <channel>
    <title>Revision3 Feed</title>
    <link>http://revision3.com/user/1564421</link>
    <description>Customized RSS Feed of all your favorite Revision3 shows.</description>
    <language>en-us</language>
    <itunes:explicit>no</itunes:explicit>
    <itunes:summary></itunes:summary>
    <itunes:subtitle></itunes:subtitle>
    <itunes:author>Revision3</itunes:author>
    <itunes:owner>
      <itunes:email>feedback@revision3.com</itunes:email>
      <itunes:name>Revision3</itunes:name>
    </itunes:owner>
    <itunes:image href="http://revision3.com/forum/image.php?u=415677" />
    <itunes:keywords />
    <image>
      <title>Revision3 Feed</title>
      <width>100</width>
      <height>100</height>
      <link>http://revision3.com/user/1564221</link>
      <url>http://revision3.com/forum/image.php?u=415677</url>
    </image>
    <atom:link rel="self" type="application/rss+xml" title="Revision3 Feed" href="http://revision3.com/feed/user/0a7ehtg09b0ab0/" />
    <item>
      <title>Tekzilla Bites - Toyota Announces New Zero-Emission Fuel Cell Vehicle For 2015!</title>
      <link>http://revision3.com/tekzillabites/toyota-fuel-cell</link>
      <description>

This year at their 2014 CES press conference, Toyota announced the Fuel Cell Vehicle (FCV): a hydrogen-powered vehicle whose only emission is water vapor going to market in 2015. Join Patrick for a look at the car, plus some of Toyota's announced specs, right from the CES show floor.

      </description>
      <content:encoded>

This year at their 2014 CES press conference, Toyota announced the Fuel Cell Vehicle (FCV): a hydrogen-powered vehicle whose only emission is water vapor going to market in 2015. Join Patrick for a look at the car, plus some of Toyota's announced specs, right from the CES show floor.

      </content:encoded>
      <author>feedback@revision3.com (Revision3)</author>
      <pubDate>Tue, 07 Jan 2014 07:00:00 GMT</pubDate>
      <itunes:image href="http://revision3.com/forum/image.php?u=415677" />
      <itunes:duration>154</itunes:duration>
      <itunes:explicit>no</itunes:explicit>
      <itunes:keywords>toyota, fuel cell vehicle, hydrogen electric, hydrogen electricity, fcv, fuel cell, water exhaust, electric car, ces 2014</itunes:keywords>
      <itunes:author>Revision3</itunes:author>
      <itunes:subtitle>
This year at their 2014 CES press conference, Toyota announced the Fuel Cell Vehicle (FCV): a hydrogen-powered vehicle whose only emission is water vapor going to market in 2015. Join Patrick for a look at the car, plus some of Toyota's announced specs,
      </itunes:subtitle>
      <guid isPermaLink="false">/tekzilla/tekzillabites/0025/tekzilla--tekzillabites--0025--toyota-fuel-cell--hd720p30.h264.mp4</guid>
      <enclosure url="http://videos.revision3.com/revision3/web/tekzilla/tekzillabites/0025/tekzilla--tekzillabites--0025--toyota-fuel-cell--hd720p30.h264.mp4" length="27874999" type="video/mp4" />
      <media:content duration="154" medium="video" fileSize="27874999" url="http://videos.revision3.com/revision3/web/tekzilla/tekzillabites/0025/tekzilla--tekzillabites--0025--toyota-fuel-cell--hd720p30.h264.mp4" type="video/mp4">
        <media:title>Tekzilla Bites - Toyota Announces New Zero-Emission Fuel Cell Vehicle For 2015!</media:title>
        <media:description>

This year at their 2014 CES press conference, Toyota announced the Fuel Cell Vehicle (FCV): a hydrogen-powered vehicle whose only emission is water vapor going to market in 2015. Join Patrick for a look at the car, plus some of Toyota's announced specs, right from the CES show floor.

        </media:description>
        <media:thumbnail url="http://videos.revision3.com/revision3/images/shows/tekzilla/tekzillabites/0025/tekzilla--tekzillabites--0025--toyota-fuel-cell--marge.thumb.jpg" width="640" height="360" />
        <media:thumbnail url="http://videos.revision3.com/revision3/images/shows/tekzilla/tekzillabites/0025/tekzilla--tekzillabites--0025--toyota-fuel-cell--medium.thumb.jpg" width="300" height="169" />
        <media:thumbnail url="http://videos.revision3.com/revision3/images/shows/tekzilla/tekzillabites/0025/tekzilla--tekzillabites--0025--toyota-fuel-cell--mini.thumb.jpg" width="100" height="100" />
        <media:player url="http://revision3.com/tekzillabites/toyota-fuel-cell" />
        <media:rating>nonadult</media:rating>
        <media:keywords>toyota, fuel cell vehicle, hydrogen electric, hydrogen electricity, fcv, fuel cell, water exhaust, electric car, ces 2014</media:keywords>
      </media:content>
      <ddn:id>28583</ddn:id>
    </item>
    <item>
      <title>Film Riot - Mondays: Getting Recognized, Poster Credits & Royalty Free Music!</title>
      <link>http://revision3.com/filmriot/poster-credits</link>
      <description>
Ryan opens up the mail sack and answers some questions!
      </description>
      <content:encoded>
Ryan opens up the mail sack and answers some questions!
      </content:encoded>
      <author>feedback@revision3.com (Revision3)</author>
      <pubDate>Tue, 07 Jan 2014 05:00:00 GMT</pubDate>
      <itunes:image href="http://revision3.com/forum/image.php?u=415677" />
      <itunes:duration>522</itunes:duration>
      <itunes:explicit>no</itunes:explicit>
      <itunes:keywords>getting recognized, getting yourself out there, poster credits, royalty free music, music, getting permission to use music, film riot, mail sack, questions, answers, q&a, ryan connolly</itunes:keywords>
      <itunes:author>Revision3</itunes:author>
      <itunes:subtitle>
Ryan opens up the mail sack and answers some questions!
      </itunes:subtitle>
      <guid isPermaLink="false">/filmriot/0364/filmriot--0364--poster-credits--hd720p30.h264.mp4</guid>
      <enclosure url="http://videos.revision3.com/revision3/web/filmriot/0364/filmriot--0364--poster-credits--hd720p30.h264.mp4" length="73676325" type="video/mp4" />
      <media:content duration="522" medium="video" fileSize="73676325" url="http://videos.revision3.com/revision3/web/filmriot/0364/filmriot--0364--poster-credits--hd720p30.h264.mp4" type="video/mp4">
        <media:title>Film Riot - Mondays: Getting Recognized, Poster Credits & Royalty Free Music!</media:title>
        <media:description>
Ryan opens up the mail sack and answers some questions!
        </media:description>
        <media:thumbnail url="http://videos.revision3.com/revision3/images/shows/filmriot/0364/filmriot--0364--poster-credits--marge.thumb.jpg" width="640" height="360" />
        <media:thumbnail url="http://videos.revision3.com/revision3/images/shows/filmriot/0364/filmriot--0364--poster-credits--medium.thumb.jpg" width="300" height="169" />
        <media:thumbnail url="http://videos.revision3.com/revision3/images/shows/filmriot/0364/filmriot--0364--poster-credits--mini.thumb.jpg" width="100" height="100" />
        <media:player url="http://revision3.com/filmriot/poster-credits" />
        <media:rating>nonadult</media:rating>
        <media:keywords>getting recognized, getting yourself out there, poster credits, royalty free music, music, getting permission to use music, film riot, mail sack, questions, answers, q&a, ryan connolly</media:keywords>
      </media:content>
      <ddn:id>28579</ddn:id>
    </item>
    <item>
      <title>Tekzilla Bites - Roku's Smart TV, More Channels, No Box- CES 2014</title>
      <link>http://revision3.com/tekzillabites/roku-tv-ces-2014</link>
      <description>

Roku known for their ever popular line up of stand-alone media streaming devices, shook things up at CES 2014 this year. Enter: Roku TV, a TV with the Roku platform baked in and a few new extras that will surprise even veteran Roku users. Patrick Norton has the details.

      </description>
      <content:encoded>

Roku known for their ever popular line up of stand-alone media streaming devices, shook things up at CES 2014 this year. Enter: Roku TV, a TV with the Roku platform baked in and a few new extras that will surprise even veteran Roku users. Patrick Norton has the details.

      </content:encoded>
      <author>feedback@revision3.com (Revision3)</author>
      <pubDate>Tue, 07 Jan 2014 05:00:00 GMT</pubDate>
      <itunes:image href="http://revision3.com/forum/image.php?u=415677" />
      <itunes:duration>105</itunes:duration>
      <itunes:explicit>no</itunes:explicit>
      <itunes:keywords>roku tv, roku, tcl, hisense, ces2014, ces 2014, roku lt, ruku 1, streaming, stream, media, tekzilla, roku remote, set top box, coard cutting</itunes:keywords>
      <itunes:author>Revision3</itunes:author>
      <itunes:subtitle>
Roku known for their ever popular line up of stand-alone media streaming devices, shook things up at CES 2014 this year. Enter: Roku TV, a TV with the Roku platform baked in and a few new extras that will surprise even veteran Roku users. Patrick Norton
      </itunes:subtitle>
      <guid isPermaLink="false">/tekzilla/tekzillabites/0024/tekzilla--tekzillabites--0024--roku-tv-ces-2014--hd720p30.h264.mp4</guid>
      <enclosure url="http://videos.revision3.com/revision3/web/tekzilla/tekzillabites/0024/tekzilla--tekzillabites--0024--roku-tv-ces-2014--hd720p30.h264.mp4" length="21262105" type="video/mp4" />
      <media:content duration="105" medium="video" fileSize="21262105" url="http://videos.revision3.com/revision3/web/tekzilla/tekzillabites/0024/tekzilla--tekzillabites--0024--roku-tv-ces-2014--hd720p30.h264.mp4" type="video/mp4">
        <media:title>Tekzilla Bites - Roku's Smart TV, More Channels, No Box- CES 2014</media:title>
        <media:description>

Roku known for their ever popular line up of stand-alone media streaming devices, shook things up at CES 2014 this year. Enter: Roku TV, a TV with the Roku platform baked in and a few new extras that will surprise even veteran Roku users. Patrick Norton has the details.

        </media:description>
        <media:thumbnail url="http://videos.revision3.com/revision3/images/shows/tekzilla/tekzillabites/0024/tekzilla--tekzillabites--0024--roku-tv-ces-2014--marge.thumb.jpg" width="640" height="360" />
        <media:thumbnail url="http://videos.revision3.com/revision3/images/shows/tekzilla/tekzillabites/0024/tekzilla--tekzillabites--0024--roku-tv-ces-2014--medium.thumb.jpg" width="300" height="169" />
        <media:thumbnail url="http://videos.revision3.com/revision3/images/shows/tekzilla/tekzillabites/0024/tekzilla--tekzillabites--0024--roku-tv-ces-2014--mini.thumb.jpg" width="100" height="100" />
        <media:player url="http://revision3.com/tekzillabites/roku-tv-ces-2014" />
        <media:rating>nonadult</media:rating>
        <media:keywords>roku tv, roku, tcl, hisense, ces2014, ces 2014, roku lt, ruku 1, streaming, stream, media, tekzilla, roku remote, set top box, coard cutting</media:keywords>
      </media:content>
      <ddn:id>28582</ddn:id>
    </item>
  </channel>
</rss>

The entire media:content block is not deserialized from the XML passed in.
I've iterated over the entire element extensions block using

foreach (SyndicationElementExtension extension in item.ElementExtensions)

but its not in there.
Is there any way I can tell the SyndicationFeed.Load() method to also parse this block for me:

SyndicationFeed feed = SyndicationFeed.Load(xmlReader);

Body:
I added an extension method for the SyndicationItem class.  Just create a class called 'ExtensionMethods.cs' in the root of your project and use the code below.  Be sure to change the namespace to match that of your project.

using System;

namespace RFAnnouncer
{
    public static class ExtensionMethods
    {
        public static string GetEnclosureUri(this System.ServiceModel.Syndication.SyndicationItem item)
        {
            for (int i = 0; i < item.Links.Count; i++)
            {
                if (item.Links[i].RelationshipType == "enclosure")
                {
                    return item.Links[i].Uri.AbsoluteUri;
                }
            }
            return "";
        }
    }
}


问:
How to get full name of month from date in Java 8 while formatting
Using new Java 8 java.time API, I need to convert LocalDate and get full name of month and day. Like March (not Mar), and Monday (not Mon). Friday the 13th March should be formatted like Friday, 13 March.. not Fri, 13 Mar.</p>

答:
Yes. Now it can be done.  </p>

```<code>LocalDate dd = new LocalDate();  //pass in a date value or params(yyyy,mm)

String ss = dd.monthOfYear.getAsText(); // will give the full name of the month
String sh = dd.monthOfYear.getAsShortText(); // shortform
</code>```

Body:
Yes. Now it can be done.

LocalDate dd = new LocalDate();  //pass in a date value or params(yyyy,mm)

String ss = dd.monthOfYear.getAsText(); // will give the full name of the month
String sh = dd.monthOfYear.getAsShortText(); // shortform


问:
Should I use DataTemplates or a UserControl to show different controls for extended classes?
I have a User class and an Author class that extends User. I have an ObservableCollection<User> being displayed in a ListBox. For this, I have a DataTemplate to display each item and another to display each selected item. I also have a column of TextBoxes that are bound to the properties of the ListBox.SelectedItem property. So far, so good.

At the moment, I am displaying extra controls in the column and DataTemplates if the selected User is an Author and it all works fine, but I'm cheating. I have added an IsAuthor bool property into the User class so that I could bind to it and determine whether a User was an Author. I know it's wrong, but I couldn't work out any other way to do it, so my first question is how do you display extended classes differently from the base class? I tried a different DataTemplate for the type Author, but it never worked... maybe because the collection was of type User?

The second question is should I have all of the many TextBox controls in the column in a UserControl and change the Visibility of the Author related controls, or somehow put them in a DataTemplate and create one for each type? I am using the first method currently and the problem is that each control bound to an Author property is throwing errors (I can see them in the Output window in Visual Studio) when the currently selected item is not an Author.

答:
I have a similar setup which uses data templates and it works just fine with inherited classes.  This is how I did it.

```<code><ListBox Name="UserList" ItemsSource="{Binding Path=Users}"
         ItemTemplate="{StaticResource ShowUserName}"
         SelectedItem="{Binding Path=SelectedUser, Mode=TwoWay}">
</ListBox>
<ContentControl Content="{Binding ElementName=UserList, Path=SelectedItem}"/>
</code>```

In the Window.Resources section I have the following DataTemplates:

```<code><DataTemplate x:Key="ShowTime" DataType="TestApp.User">
    <TextBlock Text="{Binding Path=Name}" HorizontalAlignment="Center"/>
</DataTemplate>
<DataTemplate DataType="{x:Type local:User}">
   <StackPanel Margin="10">
     <TextBlock Text="{Binding Path=Name}"/>
     <TextBlock Text="{Binding Path=Age}"/>
   </StackPanel>
</DataTemplate>
<DataTemplate DataType="{x:Type local:Author}">
   <StackPanel Margin="10">
     <TextBlock Text="{Binding Path=Name}"/>
     <TextBlock Text="{Binding Path=Age}"/>
     <TextBlock Text="{Binding Path=FirstTitle}"/>
   </StackPanel>
</DataTemplate>
</code>```

The first template is what will be displayed in the list itself.  We are referencing it by key in the ItemTemplate property of the listbox.  The other two data templates are used by the content control when determining what to display for the selected item.  When the selected item is just a User, the User DataTemplate will be displayed, if an author is selected, the author DataTemplate will be shown.

The x:Type local:Author is referring to the the class type.  local should be declared in your namespace declarations.

```<code>xmlns:local="clr-namespace:TestApp"
</code>```

Keep in mind that this is my namespace, you will have to specify the one you are using.  And of course the data templates are just basic examples, presumably you will want to do something more tailored to your application.

However it might be irritating to have to define two separate Data templates that are almost exactly the same for your two classes.  Although you certainly could.  I do it in my own application (not in this example), because what I want to display for each type are vastly different.

So what might be useful is to create a common DataTemplate for all the User properties, and simply extend this DataTemplate for Authors.  If you want to do that you could set up your templates this way:

```<code><DataTemplate x:Key="UserTemplate">
  <!-- show all the properties of the user class here -->
</DataTemplate>
<DataTemplate DataType="{x:Type local:User}">
  <ContentPresenter Content="{Binding}" ContentTemplate="{StaticResource UserTemplate}"/>
</DataTemplate>
<DataTemplate DataType="{x:Type local:Author}">
  <StackPanel>
    <ContentPresenter Content="{Binding}" ContentTemplate="{StaticResource UserTemplate}"/>
    <!-- show all the additional Author properties here -->
  </StackPanel>
</DataTemplate>
</code>```

So as you can see, both of the DataTemplates for User and for Author start out using the DataTemplate called "UserTemplate". But in the Author DataTemplate we will add Author specific properties.

I hope that helps.

Body:
I have a similar setup which uses data templates and it works just fine with inherited classes.  This is how I did it.

<ListBox Name="UserList" ItemsSource="{Binding Path=Users}"
         ItemTemplate="{StaticResource ShowUserName}"
         SelectedItem="{Binding Path=SelectedUser, Mode=TwoWay}">
</ListBox>
<ContentControl Content="{Binding ElementName=UserList, Path=SelectedItem}"/>

In the Window.Resources section I have the following DataTemplates:

<DataTemplate x:Key="ShowTime" DataType="TestApp.User">
    <TextBlock Text="{Binding Path=Name}" HorizontalAlignment="Center"/>
</DataTemplate>
<DataTemplate DataType="{x:Type local:User}">
   <StackPanel Margin="10">
     <TextBlock Text="{Binding Path=Name}"/>
     <TextBlock Text="{Binding Path=Age}"/>
   </StackPanel>
</DataTemplate>
<DataTemplate DataType="{x:Type local:Author}">
   <StackPanel Margin="10">
     <TextBlock Text="{Binding Path=Name}"/>
     <TextBlock Text="{Binding Path=Age}"/>
     <TextBlock Text="{Binding Path=FirstTitle}"/>
   </StackPanel>
</DataTemplate>

The first template is what will be displayed in the list itself.  We are referencing it by key in the ItemTemplate property of the listbox.  The other two data templates are used by the content control when determining what to display for the selected item.  When the selected item is just a User, the User DataTemplate will be displayed, if an author is selected, the author DataTemplate will be shown.

The x:Type local:Author is referring to the the class type.  local should be declared in your namespace declarations.

xmlns:local="clr-namespace:TestApp"

Keep in mind that this is my namespace, you will have to specify the one you are using.  And of course the data templates are just basic examples, presumably you will want to do something more tailored to your application.

However it might be irritating to have to define two separate Data templates that are almost exactly the same for your two classes.  Although you certainly could.  I do it in my own application (not in this example), because what I want to display for each type are vastly different.

So what might be useful is to create a common DataTemplate for all the User properties, and simply extend this DataTemplate for Authors.  If you want to do that you could set up your templates this way:

<DataTemplate x:Key="UserTemplate">
  <!-- show all the properties of the user class here -->
</DataTemplate>
<DataTemplate DataType="{x:Type local:User}">
  <ContentPresenter Content="{Binding}" ContentTemplate="{StaticResource UserTemplate}"/>
</DataTemplate>
<DataTemplate DataType="{x:Type local:Author}">
  <StackPanel>
    <ContentPresenter Content="{Binding}" ContentTemplate="{StaticResource UserTemplate}"/>
    <!-- show all the additional Author properties here -->
  </StackPanel>
</DataTemplate>

So as you can see, both of the DataTemplates for User and for Author start out using the DataTemplate called "UserTemplate". But in the Author DataTemplate we will add Author specific properties.

I hope that helps.


问:
Least points that can traverse all points in the directed graph
Given directed graph, find the minimum set of vertices that can traverse all the vertices in the graph.

```<code>E.g:
    5 -> 4
    4 -> 6
    6 -> 7
    5 -> 8
</code>```

In the above example, the minimum set of vertices will be "5", as you can visit all other vertices from vertex 5.

Is this doable using BFS or DFS?I think Kosaraju's algorithm might work, but checking if there is a easy way to do this.

答: A simple approach that you can use in order to find the minimum set of vertices is to enumerate every possible traversal for the graph and return the minimum solution.</p>

Body:
Given directed graph, find the minimum set of vertices that can traverse all the vertices in the graph.

E.g:
    5 -> 4
    4 -> 6
    6 -> 7
    5 -> 8

In the above example, the minimum set of vertices will be "5", as you can visit all other vertices from vertex 5.

Is this doable using BFS or DFS?I think Kosaraju's algorithm might work, but checking if there is a easy way to do this.