问:
Why Vue.js needs to be add in the body tag
I added my vue.js in the header but it has an error that says element root can't be found, because I have a div with an id of root.

But when I add it on the body everything works fine.

This is my js code.

```<code>new Vue({
     el: '#root'
});
</code>```

And this is my html.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

    <task-list>

    </task-list>

```

答:
you need to import your vue js library at the bottom part of your body because your #app HTML container needs to be loaded first before it can be analysed by vue js.

```<code><div id="app">
</div>
<script src="vue.js"></script>
</code>```

Body:
I added my vue.js in the header but it has an error that says element root can't be found, because I have a div with an id of root.

But when I add it on the body everything works fine.

This is my js code.

new Vue({
     el: '#root'
});

And this is my html.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

    <task-list>

    </task-list>

Body:
you need to import your vue js library at the bottom part of your body because your #app HTML container needs to be loaded first before it can be analysed by vue js.

<body>

<div id="app">
</div>
<script src="vue.js"></script>

</body>


来源: stackexchange

问:
Not able to set the dropdown value
I am not able to set the selected option of the dropdown from jquery and I am not sure whether the problem is with finding the dropdrown or issue with the code. I tried all different four ways but no result.
HTML

```<code>   <select class="form-control input-sm ddlFieldName" data-val="true" data-val-number="The field FieldTagNameId must be a number." data-val-required="The FieldTagNameId field is required."  name="FieldName">
    <option value="">----Select----</option>
    <option value="1">Property Street Address 1</option>
    <option value="2">Property Street Address 2</option>
    <option value="3">Property City</option>
    <option value="4">Property State Abbrev</option>
    <option value="5">Property Zip Code</option>
    </select>
</code>```

I have tried the following options

     var setValues;
            $(document).ready(function(){
                setValues = function(fieldName)
                {
                   //1 st method
                   $('.ddlFieldName').val(fieldName);

                    $(".ddlFieldName > [value=fieldName]").attr("selected", "true");
                   //2. Method
jQuery(".ddlFieldName").find("option:contains(fieldName)").each(function()
                    {
                     if( jQuery(this).text() === fieldName )
                     {
                           jQuery(this).attr("selected","selected");
                       }
                    });
                    //3rd method
                    document.getElementById('.ddlFieldName').value = "fieldName";
                 // 4 method
    $(".ddlFieldName > [value=" + fieldName + "]").attr("selected", "true");

                }

        });```

Thanks

答:
Ok we will start with method number 4.. you need to use .filter() and .prop("selected", true)

var setValues;
$(document).ready(function(){
    setValues = function(fieldName)
    {
     // 4 method
      $(".ddlFieldName > option").filter(function(){
      return $(this).text() == fieldName
      }).prop("selected", true);
    }
    setValues('Property City'); // run the function
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <select class="form-control input-sm ddlFieldName" data-val="true" data-val-number="The field FieldTagNameId must be a number." data-val-required="The FieldTagNameId field is required."  name="FieldName">
    <option value="">----Select----</option>
    <option value="1">Property Street Address 1</option>
    <option value="2">Property Street Address 2</option>
    <option value="3">Property City</option>
    <option value="4">Property State Abbrev</option>
    <option value="5">Property Zip Code</option>
</select></code>```

With method number 2

var setValues;
$(document).ready(function(){
    setValues = function(fieldName)
    {
     // 2 method
      $(".ddlFieldName > option:contains("+fieldName+")").prop("selected", true);
    }
    setValues('Property City'); // run the function
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <select class="form-control input-sm ddlFieldName" data-val="true" data-val-number="The field FieldTagNameId must be a number." data-val-required="The FieldTagNameId field is required."  name="FieldName">
    <option value="">----Select----</option>
    <option value="1">Property Street Address 1</option>
    <option value="2">Property Street Address 2</option>
    <option value="3">Property City</option>
    <option value="4">Property State Abbrev</option>
    <option value="5">Property Zip Code</option>
</select></code>```

ContentLicense: CC BY-SA 3.0

Title: Not able to set the dropdown value

Body:
I am not able to set the selected option of the dropdown from jquery and I am not sure whether the problem is with finding the dropdrown or issue with the code. I tried all different four ways but no result.
HTML

   <select class="form-control input-sm ddlFieldName" data-val="true" data-val-number="The field FieldTagNameId must be a number." data-val-required="The FieldTagNameId field is required."  name="FieldName">
    <option value="">----Select----</option>
    <option value="1">Property Street Address 1</option>
    <option value="2">Property Street Address 2</option>
    <option value="3">Property City</option>
    <option value="4">Property State Abbrev</option>
    <option value="5">Property Zip Code</option>
    </select>

I have tried the following options

     var setValues;
            $(document).ready(function(){
                setValues = function(fieldName)
                {
                   //1 st method
                   $('.ddlFieldName').val(fieldName);

                    $(".ddlFieldName > [value=fieldName]").attr("selected", "true");
                   //2. Method
jQuery(".ddlFieldName").find("option:contains(fieldName)").each(function()
                    {
                     if( jQuery(this).text() === fieldName )
                     {
                           jQuery(this).attr("selected","selected");
                       }
                    });
                    //3rd method
                    document.getElementById('.ddlFieldName').value = "fieldName";
                 // 4 method
    $(".ddlFieldName > [value=" + fieldName + "]").attr("selected", "true");

                }

        });

Thanks

Body:
Ok we will start with method number 4.. you need to use .filter() and .prop("selected", true)

var setValues;
$(document).ready(function(){
    setValues = function(fieldName)
    {
     // 4 method
      $(".ddlFieldName > option").filter(function(){
      return $(this).text() == fieldName
      }).prop("selected", true);
    }
    setValues('Property City'); // run the function
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <select class="form-control input-sm ddlFieldName" data-val="true" data-val-number="The field FieldTagNameId must be a number." data-val-required="The FieldTagNameId field is required."  name="FieldName">
    <option value="">----Select----</option>
    <option value="1">Property Street Address 1</option>
    <option value="2">Property Street Address 2</option>
    <option value="3">Property City</option>
    <option value="4">Property State Abbrev</option>
    <option value="5">Property Zip Code</option>
</select>

With method number 2

var setValues;
$(document).ready(function(){
    setValues = function(fieldName)
    {
     // 2 method
      $(".ddlFieldName > option:contains("+fieldName+")").prop("selected", true);
    }
    setValues('Property City'); // run the function
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <select class="form-control input-sm ddlFieldName" data-val="true" data-val-number="The field FieldTagNameId must be a number." data-val-required="The FieldTagNameId field is required."  name="FieldName">
    <option value="">----Select----</option>
    <option value="1">Property Street Address 1</option>
    <option value="2">Property Street Address 2</option>
    <option value="3">Property City</option>
    <option value="4">Property State Abbrev</option>
    <option value="5">Property Zip Code</option>
</select>


问:
If input value is blank, assign a value of "empty" with Javascript
So I have an input field, if it's blank, I want its value to be the words "empty", but if there is any value inputted, I want the value to be the inputted value. I want to use javascript for this, any idea how this can be done?

UPDATE: Sorry, I don't think I explained it too well. I don't mean placeholder text. I mean the captured value of it. So if it's blank, the captured val() for it should be "empty", if it's filled, the captured val() for it should be that val()

答:
I think the easiest way to solve this issue, if you only need it on 1 or 2 boxes is by using the HTML input's "onsubmit" function.

Check this out and i will explain what it does:

```<code><input type="text" name="val" onsubmit="if(this == ''){$this.val('empty');}" />
</code>```

So we have created the HTML text box, assigned it a name ("val" in this case) and then we added the onsubmit code, this code checks to see if the current input box is empty and if it is, then, upon form submit it will fill it with the words empty.

Please note, this code should also function perfectly when using the HTML "Placeholder" tag as the placeholder tag doesn't actually assign a value to the input box.

Body:
I think the easiest way to solve this issue, if you only need it on 1 or 2 boxes is by using the HTML input's "onsubmit" function.

Check this out and i will explain what it does:

<input type="text" name="val" onsubmit="if(this == ''){$this.val('empty');}" />

So we have created the HTML text box, assigned it a name ("val" in this case) and then we added the onsubmit code, this code checks to see if the current input box is empty and if it is, then, upon form submit it will fill it with the words empty.

Please note, this code should also function perfectly when using the HTML "Placeholder" tag as the placeholder tag doesn't actually assign a value to the input box.


问:
Passing a character variable into a function in R (Tidyjson)
I'm messing around with tidyjson (latest from github, published by Jeremy Stanley). I wanted to sort of automate searching and extract the nested arrays. The following examples below provide the output I want.

```<code>'{"name": {"first": "bob", "last": "jones"}, "age": 32}' %>%
 enter_object("name") %>%
 gather_keys %>%
 append_values_string

'{"name": {"first": "bob", "last": "jones"}, "age": 32}' %>%
 enter_object(name) %>%
 gather_keys %>%
 append_values_string
</code>```

These both give the same output:

```<code># A tbl_json: 2 x 3 tibble with a "JSON" attribute
`attr(., "JSON")` document.id   key string
          <chr>       <int> <chr>  <chr>
1             "bob"           1 first    bob
2           "jones"           1  last  jones
</code>```

However, if I declare a character variable before and pass it along it fails.

```<code>object_name <- "name"
'{"name": {"first": "bob", "last": "jones"}, "age": 32}' %>%
enter_object(list(name="name")) %>%
gather_keys %>%
append_values_string

Error: Path components must be single names or character strings
</code>```

Any ideas why this would happen?

答:
If you are familiar with Hadley's book Advanced R, this is a piece of non-standard evaluation that unfortunately does not presently have a workaround in pure tidyjson (I would prefer a enter_object_ that uses standard evaluation, more like dplyr).  I am hopeful of that functionality at some point being available, because as you suggest, it would be nice to vectorize and automate these sorts of programs.

The Non-Standard Evaluation is the "magic" that allows you to pass in the un-quoted name and still get good results in your second example (instead of the program looking for an object called name).  The hazard is it does not resolve objects like object_name in your case.

That said, it seems you can work-around with do.call and a list of parameters (I fixed your example, as I think it went a bit awry)

```<code>library(tidyjson)

json <- "{\"name\": {\"first\": \"bob\", \"last\": \"jones\"}, \"age\": 32}"
object_name <- "name"

do.call(enter_object, args = list(json, object_name)) %>% gather_object %>%
  append_values_string
#> # A tbl_json: 2 x 3 tibble with a "JSON" attribute
#>   `attr(., "JSON")` document.id  name string
#>               <chr>       <int> <chr>  <chr>
#> 1         "\"bob\""           1 first    bob
#> 2       "\"jones\""           1  last  jones
</code>```

I definitely recommend checking out some of the new features / functionality in the development version of tidyjson with devtools::install_github('jeremystan/tidyjson'), but unfortunately no support for standard evaluation in "path"s yet.

Body:
I'm messing around with tidyjson (latest from github, published by Jeremy Stanley). I wanted to sort of automate searching and extract the nested arrays. The following examples below provide the output I want.

'{"name": {"first": "bob", "last": "jones"}, "age": 32}' %>%
 enter_object("name") %>%
 gather_keys %>%
 append_values_string

'{"name": {"first": "bob", "last": "jones"}, "age": 32}' %>%
 enter_object(name) %>%
 gather_keys %>%
 append_values_string

These both give the same output:

# A tbl_json: 2 x 3 tibble with a "JSON" attribute
`attr(., "JSON")` document.id   key string
          <chr>       <int> <chr>  <chr>
1             "bob"           1 first    bob
2           "jones"           1  last  jones

However, if I declare a character variable before and pass it along it fails.

object_name <- "name"
'{"name": {"first": "bob", "last": "jones"}, "age": 32}' %>%
enter_object(list(name="name")) %>%
gather_keys %>%
append_values_string

Error: Path components must be single names or character strings

Any ideas why this would happen?

Body:
If you are familiar with Hadley's book Advanced R, this is a piece of non-standard evaluation that unfortunately does not presently have a workaround in pure tidyjson (I would prefer a enter_object_ that uses standard evaluation, more like dplyr).  I am hopeful of that functionality at some point being available, because as you suggest, it would be nice to vectorize and automate these sorts of programs.

The Non-Standard Evaluation is the "magic" that allows you to pass in the un-quoted name and still get good results in your second example (instead of the program looking for an object called name).  The hazard is it does not resolve objects like object_name in your case.

That said, it seems you can work-around with do.call and a list of parameters (I fixed your example, as I think it went a bit awry)

library(tidyjson)

json <- "{\"name\": {\"first\": \"bob\", \"last\": \"jones\"}, \"age\": 32}"
object_name <- "name"

do.call(enter_object, args = list(json, object_name)) %>% gather_object %>%
  append_values_string
#> # A tbl_json: 2 x 3 tibble with a "JSON" attribute
#>   `attr(., "JSON")` document.id  name string
#>               <chr>       <int> <chr>  <chr>
#> 1         "\"bob\""           1 first    bob
#> 2       "\"jones\""           1  last  jones

I definitely recommend checking out some of the new features / functionality in the development version of tidyjson with devtools::install_github('jeremystan/tidyjson'), but unfortunately no support for standard evaluation in "path"s yet.


问:
What is the reason ES6 class constructors can't be called as normal functions?
ES6 class constructors can't be called as normal functions. According to ES6 a TypeError should be raised when this is done. I used to think that classes were just syntactic sugar for a constructor function + functions in the prototype, but this makes it slightly not so.

I'm wondering, what was the rationale behind this? Unless I missed something, it prevents calling the function with a custom this, which could be desirable for some patterns.

答:
A revisit to the ES6 spec shows how calling a Class function object without new is disabled by combining sections 9.2.9 and 9.2.1:

9.2.9 MakClassConstructor (F)

  ...

  3. Set F’s [[FunctionKind]] internal slot to "classConstructor".

and when specifying the [[call]] method as opposed to the [[contruct]] method of a function:

(9.2.1) 2. If F’s [[FunctionKind]] internal slot is "classConstructor", throw a TypeError exception.

No restrictions are placed on calling function in section "11.2.3 "Function calls" of ES5.1.

So you are not missing anything: you can't use apply on a class constructor function.

The major rationale is probably both to make class extensions a fairly rigorous exercise, and to detect some early forms of error. For example you can't call Promise except as a constructor - and leaving out new before a call to Promise is a programming error. In regards extending classes, note that the constructor property of class instances is correctly set (the last class after possibly multiple extensions) and the the .prototype property of the class constructor is read only - you can't dynamically change the prototype object used to construct class instances, even though you could change the prototype property of a constructor function.

I used to think classes were syntactic sugar but have moved away from the concept.


问:
Modal on desktop
Can you help me with this,

Im working on e-commerce site, so in the cart page i have have one link,

BUTTON LINK

At the moment you are directed to https://www.example/nexpageform when click on this link.
 I want the visitor to stay on the this page and when you click button you got modal and in that modal you get data from next page.

Important thing for me that this Only has to run on desktop, so mobile and tablets has old option and ONLY desktop got modal.

1) Im confused with approach on this, because i need to have modal on desktop and on smaller devices i need to have redirect to another page.

If someone can show me right way or approach I would be grateful.

Thank you

答:
You can create two anchor tags with different classes or IDs and display them based on CSS media queries.

$(document).ready(function(){
  $('.desktop-only-link').on('click', function(e){
    e.preventDefault();

    $('
')
      .append('
')
      .text('This is a dialog popup')
      .dialog({
        title: 'Your Title Here'
      });
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.mobile-only-link {
  display: none;
  color: red;
}

@media screen and (max-width: 480px) {
  .desktop-only-link {
    display: none;
  }
  .mobile-only-link {
    display: inline;
  }
}</code>```

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">

BUTTON LINK
BUTTON LINK```

Title: Modal on desktop

Body:
You can create two anchor tags with different classes or IDs and display them based on CSS media queries.

$(document).ready(function(){
  $('.desktop-only-link').on('click', function(e){
    e.preventDefault();

    $('<div />')
      .append('<p>')
      .text('This is a dialog popup')
      .dialog({
        title: 'Your Title Here'
      });
  });
});

.mobile-only-link {
  display: none;
  color: red;
}

@media screen and (max-width: 480px) {
  .desktop-only-link {
    display: none;
  }
  .mobile-only-link {
    display: inline;
  }
}

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<a href="https://www.example/nexpageform" class="mobile-only-link">BUTTON LINK</a>
<a href="#" class="desktop-only-link">BUTTON LINK</a>


问:
Boostrap image not responsive in safari
I  realized my website is not working on safari (desktop and mobile). For some reason the images are not responsive. I used a Bootstrap theme, the website is simple. Please help!

website: www.scanek.com

HTML:

```<code><section id="portfolio" class="pfblock">
    <div class="container">
        <div class="row">

            <div class="col-sm-6 col-sm-offset-3">

                <div class="pfblock-header wow fadeInUp">
                    <h2 class="pfblock-title">Categories</h2>
                    <div class="pfblock-subtitle">

                    </div>
                </div>

            </div>

        </div><!-- .row -->

        <div class="row">

            <div class="col-xs-12 col-sm-6 col-md-4 col-lg-4">
                <div class="grid wow zoomIn">
                    <a href="categories/kitchen/index.html">
                    <figure class="effect-bubba">
                        <img src="assets/images/kitchens.jpg" alt="img01" class="img-responsive" />
                        <figcaption>
                            <h2> <span>Kitchens</span></h2>
                            <p></p>
                        </figcaption>
                    </figure>
                    </a>
                </div>

            </div>

            <div class="col-xs-12 col-sm-6  col-md-4 col-lg-4">
                <div class="grid wow zoomIn">
                    <a href="categories/bathroom//bathroom1/index.html">
                    <figure class="effect-bubba">
                        <img src="assets/images/bathrooms.jpg" alt="img01"/>
                        <figcaption>
                            <h2> <span>Bathrooms</span></h2>
                            <p></p>
                        </figcaption>
                    </figure>
                    </a>
                </div>

            </div>

            <div class="col-xs-12 col-sm-6 col-md-4 col-lg-4">
                <div class="grid wow zoomIn">
                   <a href="categories/fixtures/index.html">
                    <figure class="effect-bubba">
                        <img src="assets/images/fixtures.jpg" alt="img01"/>
                        <figcaption>
                            <h2>House<span> Fixtures</span></h2>
                            <p></p>
                        </figcaption>
                    </figure>
                    </a>
                </div>

            </div>

        </div>

    </div><!-- .container -->

</section>
</code>```

CSS:

```<code>img {
max-width: 100%;
width: 100%;
height: auto;
}

.grid figure img {
position: relative;
display: block;
min-height: 100%;
max-width: 100%;
opacity: 0.8;

}

figure.effect-bubba img {
opacity: 0.75;
-webkit-transition: opacity 0.35s;
transition: opacity 0.35s;
}
</code>```

答:
Your css syntaks on link that you provide to us is not right, for the start,
you have:

```<code>img {
    max-width: 100% width :100% height: auto;
}
</code>```

try with :

```<code>img {
 max-width: 100%;
 width :100%;
 height: auto;
}
</code>```

after yo fix this issues, then if problem is still there we can try to help you..

Title: Boostrap image not responsive in safari

Body:
I  realized my website is not working on safari (desktop and mobile). For some reason the images are not responsive. I used a Bootstrap theme, the website is simple. Please help!

website: www.scanek.com

HTML:

Categories

 Kitchens

 Bathrooms

House Fixtures

CSS:

img {
max-width: 100%;
width: 100%;
height: auto;
}

.grid figure img {
position: relative;
display: block;
min-height: 100%;
max-width: 100%;
opacity: 0.8;

}

figure.effect-bubba img {
opacity: 0.75;
-webkit-transition: opacity 0.35s;
transition: opacity 0.35s;
}

Body:
Your css syntaks on link that you provide to us is not right, for the start,
you have:

img {
    max-width: 100% width :100% height: auto;
}

try with :

img {
 max-width: 100%;
 width :100%;
 height: auto;
}

after yo fix this issues, then if problem is still there we can try to help you..


问:
Linux command on wake up from hibernate/suspend
I'm new to Linux and running Mint. I've seen a lot of documentation on creating commands that run when the os is started up from the computer being powered off. Is there a way to make similar commands to run when the os wakes up from hibernate or suspend? (For context, I'm running 'rfkill block bluetooth' on startup and would like to when my pc wakes up from hibernate as well).</p>

答:
place your commands in a script file and ensure you have sufficient owner/permissions to execute in  /lib/systemd/system-sleep/ so once your OS suspends from sleep, its going to execute.

For more information
man systemd-sleep

https://askubuntu.com/questions/226278/run-script-on-wakeup


问:
Why doesn't this SQL statement work?
```
SELECT * FROM table1, table2
WHERE table1.user_id = table2.id
AND table1.content = news
AND table1.content_id = 1
```

that wont work. cant u have two "AND" in a sql statement??

//Tomek

答: news is what? Some sort of parameter? Value of the field? A word which should occur in the field? Most likely your syntax is wrong, see W3Schools WHERE and W3Schools AND/OR operators pages for more information.

OwnerDisplayName: Tomek

LastEditorDisplayName: Graeme Perrow

ContentLicense: CC BY-SA 2.5

Title: Why doesn't this SQL statement work?

Body:
SELECT * FROM table1, table2
WHERE table1.user_id = table2.id
AND table1.content = news
AND table1.content_id = 1

that wont work. cant u have two "AND" in a sql statement??

//Tomek

OwnerDisplayName: Esko


问:
ios app is crashing
I'm having a problem with my app crashing. The main root controller is a tab controller. inside the tab controller i have 4 buttons that have a nav controllers hooked up to them. inside the nav controller, i have a table controller with a few cells. when you click a cell, it takes you to a view controller. now when i click on the cell and it takes me to the view controller. when i click on the back arrow on the nav controller, it takes me back to the table view, which is great, but when i click on a new cell, the app crashes. everytime i click a cell, go back, and click another cell, the app crashes. what am i doing wrong? i think i too care of all my releases. not sure though.

Theres an error I get when I run the program. It reads:

Book Nav Controller (Medical How To's) has it 'NIB Name" property set to 'BookTableViewController.nib', but this view controller is not intended to have its view set in this manner.

I'm also getting setText is deprecated on this code:

```<code>cell.text = [breakdownArray objectAtIndex:row];
</code>```

What do I change it to?

Also My didSelectRowAtIndexPath code is:

```<code>NSInteger row = [indexPath row];
if (self.bookDetailViewController == nil); {
    BookDetailViewController *aBookDetail = [[BookDetailViewController alloc] initWithNibName:@"BookDetailView" bundle:nil];
    self.bookDetailViewController = aBookDetail;

    [aBookDetail release];

}

bookDetailViewController.title = [NSString stringWithFormat:@"%Breakdown" , [breakdownArray objectAtIndex:row]];

Surviving2012AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
[delegate.breakdownNavController pushViewController:bookDetailViewController animated:YES];

[delegate release];

}
</code>```

答:
definitely don't call release on the delegate.
you only call release on an object when you have used a method on it which contains:
alloc/init, copy, new or retain. otherwise you are likely releasing an autoreleased instance, which will cause it to crash.

fix this, if it still happens, post your results, and we will have another look.

Title: ios app is crashing

Body:
I'm having a problem with my app crashing. The main root controller is a tab controller. inside the tab controller i have 4 buttons that have a nav controllers hooked up to them. inside the nav controller, i have a table controller with a few cells. when you click a cell, it takes you to a view controller. now when i click on the cell and it takes me to the view controller. when i click on the back arrow on the nav controller, it takes me back to the table view, which is great, but when i click on a new cell, the app crashes. everytime i click a cell, go back, and click another cell, the app crashes. what am i doing wrong? i think i too care of all my releases. not sure though.

Theres an error I get when I run the program. It reads:

Book Nav Controller (Medical How To's) has it 'NIB Name" property set to 'BookTableViewController.nib', but this view controller is not intended to have its view set in this manner.

I'm also getting setText is deprecated on this code:

cell.text = [breakdownArray objectAtIndex:row];

What do I change it to?

Also My didSelectRowAtIndexPath code is:

NSInteger row = [indexPath row];
if (self.bookDetailViewController == nil); {
    BookDetailViewController *aBookDetail = [[BookDetailViewController alloc] initWithNibName:@"BookDetailView" bundle:nil];
    self.bookDetailViewController = aBookDetail;

    [aBookDetail release];

}

bookDetailViewController.title = [NSString stringWithFormat:@"%Breakdown" , [breakdownArray objectAtIndex:row]];

Surviving2012AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
[delegate.breakdownNavController pushViewController:bookDetailViewController animated:YES];

[delegate release];

}


问:
Edit table row javascript
I have a table, that is dynamicallly increased with Firebase, and I need a delete and edit button on each row of the table, currently, the remove button is working, but I am having trouble with the edit button, I saw a few examples around, but i'm not sure how to do it using append()...

Here's what I have so far:

HTML

```<code><table id="tableAssets" class="mdl-data-table mdl-js-data-table mdl-shadow--2dp">

    <thead>
      <tr id="tableHeader">
        <th class="mdl-data-table__cell--non-numeric">Name</th>
        <th class="mdl-data-table__cell--non-numeric">Brand</th>
        <th class="mdl-data-table__cell--non-numeric"> </th>
      </tr>
    </thead>

    <tbody id="table_body"> </tbody>

</table>
</code>```

JavaScript

```<code>rootRef.on("child_added", snap => {

  var assetKey = snap.child("id").val();
  var name = snap.child("name").val();
  var brand = snap.child("brand").val();

  $("#table_body").append("<tr data-id='"+assetKey+"'>"+
                          "<td class='mdl-data-table__cell--non-numeric'>" + name + "</td>" +
                          "<td class='mdl-data-table__cell--non-numeric'>" + brand + "</td>" +

                          "<td class='mdl-data-table__cell--non-numeric'><div buttons>"+
                              "<button class='edit-btn'><i class='material-icons'>mode_edit</i></button>"+" "+
                              "<button class='delete-btn'><i class='material-icons'>delete</i></button>"+" "+
                          "</div></td></tr>");
});
</code>```

And here is what I was thinking on doing with the edit button: Hide the whole row, and add a new one with the saved information, but with text fields, and change the edit button with a save button, but I have no idea how I should be doing this...

```<code>$("#table_body").on('click','.edit-btn', function(e){
var $row = $(this).closest('tr');
  $row.hide();

});
</code>```

答:
I'd suggest you to do this:

Have two rows, one for view and one for edit mode. This is easier to
maintain.

Assign an id to the whole row:
$("#table_body").append("

Then when clicking that edit button, pass the id to some method as when you append you have it, it is easier. You can use something
like onclick and call the method:

<button class='edit-btn' onclick=edit(\'"+assetKey+"\')>mode_edit</button>

On edit, hide the clicked button row and show the edit mode for that row. As it is already rendered, it works great if you have
multiple rows, stays in place:
('#'+id).hide();

The edit mode row "view" would show the save button or anything else you need. Use the same Technique/strategy to call a save() method.

When save is successful, rebuild both rows and replace them so everything is neat and stays in line.

And to make sense of this and it is not just in words, a functional example using your code on jsfiddle here.

Hope this is of help!

Title: Edit table row javascript

Body:
I have a table, that is dynamicallly increased with Firebase, and I need a delete and edit button on each row of the table, currently, the remove button is working, but I am having trouble with the edit button, I saw a few examples around, but i'm not sure how to do it using append()...

Here's what I have so far:

HTML

        Name
        Brand

JavaScript

rootRef.on("child_added", snap => {

  var assetKey = snap.child("id").val();
  var name = snap.child("name").val();
  var brand = snap.child("brand").val();

  $("#table_body").append("
"+
                          "" + name + "	" +
                          "" + brand + "	" +

                          "
"+
                              "<button class='edit-btn'>mode_edit</button>"+" "+
                              "<button class='delete-btn'>delete</button>"+" "+
                          "

");
});

And here is what I was thinking on doing with the edit button: Hide the whole row, and add a new one with the saved information, but with text fields, and change the edit button with a save button, but I have no idea how I should be doing this...

$("#table_body").on('click','.edit-btn', function(e){
var $row = $(this).closest('tr');
  $row.hide();

});

Body:
I'd suggest you to do this:

Have two rows, one for view and one for edit mode. This is easier to
maintain.

Assign an id to the whole row:
$("#table_body").append("<tr id='"+assetKey+"'>

Then when clicking that edit button, pass the id to some method as when you append you have it, it is easier. You can use something
like onclick and call the method:

<button class='edit-btn' onclick=edit(\'"+assetKey+"\')><i class='material-icons'>mode_edit</i></button>

On edit, hide the clicked button row and show the edit mode for that row. As it is already rendered, it works great if you have
multiple rows, stays in place:
('#'+id).hide();

The edit mode row "view" would show the save button or anything else you need. Use the same Technique/strategy to call a save() method.

When save is successful, rebuild both rows and replace them so everything is neat and stays in line.

And to make sense of this and it is not just in words, a functional example using your code on jsfiddle here.

Hope this is of help!


问:
Correct way to pause a Python program
I've been using the input function as a way to pause my scripts:

```<code>print("something")
wait = input("Press Enter to continue.")
print("something")
</code>```

Is there a formal way to do this?

答:
Very simple:</p>
```<code>raw_input("Press Enter to continue ...")
print("Doing something...")
</code>```

ContentLicense: CC BY-SA 4.0

Title: Correct way to pause a Python program

Body:
I've been using the input function as a way to pause my scripts:

print("something")
wait = input("Press Enter to continue.")
print("something")

Is there a formal way to do this?

Body:
Very simple:

raw_input("Press Enter to continue ...")
print("Doing something...")


问:
React-Native AirBnb Maps not rendering
So within the constructor, I define a state

```<code>this.state = {
  markers: [{
            title: "Bike1",
            description: "Bike1",
            latitude: 38.232,
            longitude: -121.3312186
          },
          {
            title: "Bike2",
            description: "Bike2",
            latitude: 39.532,
            longitude: -123.5312186
          }]
}
</code>```

Later on, I call the function to map all markers to actual MapView.Markers.

This looks as follows:

```<code>{this.state.markers.map( marker => {
          console.log(JSON.stringify(marker));
          <MapView.Marker
          coordinate={{longitude: marker.longitude, latitude: marker.latitude}}
          title={marker.title}
          description={marker.description}
          >
          <View style={styles.bikeRadius}>
            <View style={styles.bikeMarker}></View>
          </View>
          </MapView.Marker>
        })}
</code>```

However, this works when I call a single marker.

```<code><MapView.Marker coordinate={{latitude: this.state.gpsPosition.latitude, longitude: this.state.gpsPosition.longitude}}>
        <View style={styles.radius}>
          <View style={styles.marker}></View>
        </View>
      </MapView.Marker>
</code>```

I am new to react-native and am not sure what I am doing wrong. Any suggestions?

The link to the full file is https://codepen.io/yeni/pen/QgyWPZ

答:
You're not returning anything from your map function to render. Quick fix would be to do something like this:

```<code>{this.state.markers.map( (marker, index) => {
  console.log(JSON.stringify(marker));
  return (
    <MapView.Marker
      key={index}
      coordinate={{longitude: marker.longitude, latitude: marker.latitude}}
      title={marker.title}
      description={marker.description}
    >
      <View style={styles.bikeRadius}>
        <View style={styles.bikeMarker}></View>
      </View>
    </MapView.Marker>
  )
})}
</code>```

I've also included a simple way to add a key using index from the map function as you will get a warning about that when using map in this manner.

Title: React-Native AirBnb Maps not rendering

Body:
So within the constructor, I define a state

this.state = {
  markers: [{
            title: "Bike1",
            description: "Bike1",
            latitude: 38.232,
            longitude: -121.3312186
          },
          {
            title: "Bike2",
            description: "Bike2",
            latitude: 39.532,
            longitude: -123.5312186
          }]
}

Later on, I call the function to map all markers to actual MapView.Markers.

This looks as follows:

{this.state.markers.map( marker => {
          console.log(JSON.stringify(marker));
          <MapView.Marker
          coordinate={{longitude: marker.longitude, latitude: marker.latitude}}
          title={marker.title}
          description={marker.description}
          >
          <View style={styles.bikeRadius}>
            <View style={styles.bikeMarker}></View>
          </View>
          </MapView.Marker>
        })}

However, this works when I call a single marker.

<MapView.Marker coordinate={{latitude: this.state.gpsPosition.latitude, longitude: this.state.gpsPosition.longitude}}>
        <View style={styles.radius}>
          <View style={styles.marker}></View>
        </View>
      </MapView.Marker>

I am new to react-native and am not sure what I am doing wrong. Any suggestions?

The link to the full file is https://codepen.io/yeni/pen/QgyWPZ

Body:
You're not returning anything from your map function to render. Quick fix would be to do something like this:

{this.state.markers.map( (marker, index) => {
  console.log(JSON.stringify(marker));
  return (
    <MapView.Marker
      key={index}
      coordinate={{longitude: marker.longitude, latitude: marker.latitude}}
      title={marker.title}
      description={marker.description}
    >
      <View style={styles.bikeRadius}>
        <View style={styles.bikeMarker}></View>
      </View>
    </MapView.Marker>
  )
})}

I've also included a simple way to add a key using index from the map function as you will get a warning about that when using map in this manner.


问:
Excel SUMIFS - Multiple Array
I tried to include SUMIFS with single array and it works fine:

```<code> =SUM(SUMIFS(Sheet3!H:H,Sheet3!G:G,"X",Sheet3!E:E,"SA",Sheet3!D:D,{"A","B","C"}))
</code>```

When I try to include a second array as below it gives me only the first/last item  from {"X","Y","Z"}

```<code> =SUM(SUMIFS(Sheet3!H:H,Sheet3!G:G,{"X","Y","Z"},Sheet3!E:E,"SA",Sheet3!D:D,{"A","B","C"}))
</code>```

The only workaround I could figure out is by separating the formula in 3 chunks (each item in {"X","Y","Z"}).

Is there any other work around? Or two arrays in SUMIFS does not work properly?

答:
You can use a row array for one of the lists and a column array for the other. Try this:

```<code>=SUM(SUMIFS(Sheet3!H:H, Sheet3!G:G, {"X","Y","Z"},
  Sheet3!E:E,"SA",Sheet3!D:D,{"A";"B";"C"}))
'                                ^   ^
</code>```

The inner SUMIFS makes a cross-product of the two arrays; a matrix where each entry is the "sumif" matching both the corresponding row and column elements:

```<code>        X,A      Y,A    Z,A
        X,B      Y,B    Z,B
        X,C      Y,C    Z,C
</code>```

Then the outer SUM adds up all the elements. As a result, you will have the sum where each field matches any element of it's criteria's array:

```<code>G:G is any of {"X","Y","Z"}      and      D:D is any of {"A";"B";"C"}
</code>```

Of course the other, single condition E:E="SA" applies in all cases.

The two lists don't need to have the same cardinality.

This technique cannot be generalized to more than two lists. If you had a third criteria list, you need to proceed in a different way.

Title: Excel SUMIFS - Multiple Array

Body:
I tried to include SUMIFS with single array and it works fine:

 =SUM(SUMIFS(Sheet3!H:H,Sheet3!G:G,"X",Sheet3!E:E,"SA",Sheet3!D:D,{"A","B","C"}))

When I try to include a second array as below it gives me only the first/last item  from {"X","Y","Z"}

 =SUM(SUMIFS(Sheet3!H:H,Sheet3!G:G,{"X","Y","Z"},Sheet3!E:E,"SA",Sheet3!D:D,{"A","B","C"}))

The only workaround I could figure out is by separating the formula in 3 chunks (each item in {"X","Y","Z"}).

Is there any other work around? Or two arrays in SUMIFS does not work properly?

Body:
You can use a row array for one of the lists and a column array for the other. Try this:

=SUM(SUMIFS(Sheet3!H:H, Sheet3!G:G, {"X","Y","Z"},
  Sheet3!E:E,"SA",Sheet3!D:D,{"A";"B";"C"}))
'                                ^   ^

The inner SUMIFS makes a cross-product of the two arrays; a matrix where each entry is the "sumif" matching both the corresponding row and column elements:

        X,A      Y,A    Z,A
        X,B      Y,B    Z,B
        X,C      Y,C    Z,C

Then the outer SUM adds up all the elements. As a result, you will have the sum where each field matches any element of it's criteria's array:

G:G is any of {"X","Y","Z"}      and      D:D is any of {"A";"B";"C"}

Of course the other, single condition E:E="SA" applies in all cases.

The two lists don't need to have the same cardinality.

This technique cannot be generalized to more than two lists. If you had a third criteria list, you need to proceed in a different way.


问:
Can we print error message before form begin in mvc?
can we print error message before form start, I am using mvc v4

this is my controller action code
          [HttpGet]

```<code>        public ActionResult ChangePassword(string aToken)
        {
          aToken = Server.UrlDecode(aToken);

          if (aToken != null)
          {
           .........
           }
          else
          {
      ViewBag.Error = "Sorry, this link is not being recognized as valid.
          }

    return view();`enter code here`
        }
</code>```

this is my cshtml file

```<code>    @if (ViewBag.Error != null)

    {
      <p class="text-danger">
        @ViewBag.Error
      </p>
    }
    else
    {
      using (Html.BeginForm("ChangePassword", "Account", FormMethod.Post, new {
     @class = "form-horizontal ", role = "form" }))
      {

         ........................
      }

    }`enter code here`
</code>```

technicality, is this correct?

答:
Hi we can print error message anywhere we want , according to the place we are providing the error message, it will render the page.

So as per your above code itself , viewbag will print the error message before the form begin, but one small clarification.

ViewData and TempData require typecasting and null checking whereas
  ViewBag doesn't need such checking.

It will save you few lines of code as below:

```<code> <p class="text-danger">
    @ViewBag.Error
  </p>
  using (Html.BeginForm("ChangePassword", "Account", FormMethod.Post, new {
 @class = "form-horizontal ", role = "form" }))
  {

     ........................
  }
</code>```

Additional info:http://www.binaryintellect.net/articles/36941654-8bd4-4535-9226-ddf47841892f.aspx

Hope above information was helpful

Thanks

Karthik

Body:
can we print error message before form start, I am using mvc v4

this is my controller action code
          [HttpGet]

        public ActionResult ChangePassword(string aToken)
        {
          aToken = Server.UrlDecode(aToken);

          if (aToken != null)
          {
           .........
           }
          else
          {
      ViewBag.Error = "Sorry, this link is not being recognized as valid.
          }

    return view();`enter code here`
        }

this is my cshtml file

    @if (ViewBag.Error != null)

    {

        @ViewBag.Error

    }
    else
    {
      using (Html.BeginForm("ChangePassword", "Account", FormMethod.Post, new {
     @class = "form-horizontal ", role = "form" }))
      {

         ........................
      }

    }`enter code here`

technicality, is this correct?

Body:
Hi we can print error message anywhere we want , according to the place we are providing the error message, it will render the page.

So as per your above code itself , viewbag will print the error message before the form begin, but one small clarification.

ViewData and TempData require typecasting and null checking whereas
  ViewBag doesn't need such checking.

It will save you few lines of code as below:

 <p class="text-danger">
    @ViewBag.Error
  </p>
  using (Html.BeginForm("ChangePassword", "Account", FormMethod.Post, new {
 @class = "form-horizontal ", role = "form" }))
  {

     ........................
  }

Additional info:http://www.binaryintellect.net/articles/36941654-8bd4-4535-9226-ddf47841892f.aspx

Hope above information was helpful

Thanks

Karthik


问:
Fail to install gitlab on ubuntu
Now I am trying to install gitlab for ubuntu that be hosted on a virtual machine. Its version is 15.10 and it is 64-bit. I try to install it following this tutorial. But I got such error:

```<code>Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package gitlab-ce
</code>```

The content of /etc/apt/sources.list.d/gitlab_gitlab-ce.list is :

```<code># this file was generated by packages.gitlab.com for
# the repository at https://packages.gitlab.com/gitlab/gitlab-ce

deb https://packages.gitlab.com/gitlab/gitlab-ce/ubuntu/ wily main
deb-src https://packages.gitlab.com/gitlab/gitlab-ce/ubuntu/ wily main
</code>```

Do you know how can I fix this issue? Thanks a lot in advance!

EDIT:

After I installed a ubuntu with version of 16.04, the previous error does not exist anymore. But now a new one occurs :(
When I run apt-get install gitlab-ce, I got the error of no avaliable space. I ran df -Th and here is the output

```<code>Filesystem     Type      Size  Used Avail Use% Mounted on
udev           devtmpfs  2.6G     0  2.6G   0% /dev
tmpfs          tmpfs     524M  7.7M  516M   2% /run
/dev/sda1      ext4      4.6G  4.1G  245M  95% /
tmpfs          tmpfs     2.6G   21M  2.6G   1% /dev/shm
tmpfs          tmpfs     5.0M  4.0K  5.0M   1% /run/lock
tmpfs          tmpfs     2.6G     0  2.6G   0% /sys/fs/cgroup
tmpfs          tmpfs     524M   56K  524M   1% /run/user/1000
</code>```

So there are some partitions that I can utilize. Do you know how to install the gitlab to those available partitions?

答:
https://packages.gitlab.com/gitlab/gitlab-ce

```<code>If you are not comfortable installing the repository through a piped script, you can find the entire script here and select and download the package manually and install using

curl -LJO https://packages.gitlab.com/gitlab/gitlab-ce/packages/ubuntu/xenial/gitlab-ce-XXX.deb/download
dpkg -i gitlab-ce-XXX.deb
</code>```

try using a xenial package its just one ubuntu version higher.

```<code>curl -s https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.deb.sh | sudo bash
sudo apt-get install gitlab-ce=9.2.5-ce.0
</code>```

https://packages.gitlab.com/gitlab/gitlab-ce/packages/ubuntu/xenial/gitlab-ce_9.2.5-ce.0_amd64.deb

or trusty (1 ubuntu version lower). Its been suggested that trusty has higher compatibility so you can try that first. But I agree that you should release-upgrade to ubuntu 16.04

https://packages.gitlab.com/gitlab/gitlab-ce/packages/ubuntu/trusty/gitlab-ce_9.0.10-ce.0_amd64.deb

```<code>curl -s https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.deb.sh | sudo bash
sudo apt-get install gitlab-ce=9.0.10-ce.0
</code>```

Title: Fail to install gitlab on ubuntu

Body:
Now I am trying to install gitlab for ubuntu that be hosted on a virtual machine. Its version is 15.10 and it is 64-bit. I try to install it following this tutorial. But I got such error:

Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package gitlab-ce

The content of /etc/apt/sources.list.d/gitlab_gitlab-ce.list is :

# this file was generated by packages.gitlab.com for
# the repository at https://packages.gitlab.com/gitlab/gitlab-ce

deb https://packages.gitlab.com/gitlab/gitlab-ce/ubuntu/ wily main
deb-src https://packages.gitlab.com/gitlab/gitlab-ce/ubuntu/ wily main

Do you know how can I fix this issue? Thanks a lot in advance!

EDIT:

After I installed a ubuntu with version of 16.04, the previous error does not exist anymore. But now a new one occurs :(
When I run apt-get install gitlab-ce, I got the error of no avaliable space. I ran df -Th and here is the output

Filesystem     Type      Size  Used Avail Use% Mounted on
udev           devtmpfs  2.6G     0  2.6G   0% /dev
tmpfs          tmpfs     524M  7.7M  516M   2% /run
/dev/sda1      ext4      4.6G  4.1G  245M  95% /
tmpfs          tmpfs     2.6G   21M  2.6G   1% /dev/shm
tmpfs          tmpfs     5.0M  4.0K  5.0M   1% /run/lock
tmpfs          tmpfs     2.6G     0  2.6G   0% /sys/fs/cgroup
tmpfs          tmpfs     524M   56K  524M   1% /run/user/1000

So there are some partitions that I can utilize. Do you know how to install the gitlab to those available partitions?

Body:
https://packages.gitlab.com/gitlab/gitlab-ce

If you are not comfortable installing the repository through a piped script, you can find the entire script here and select and download the package manually and install using

curl -LJO https://packages.gitlab.com/gitlab/gitlab-ce/packages/ubuntu/xenial/gitlab-ce-XXX.deb/download
dpkg -i gitlab-ce-XXX.deb

try using a xenial package its just one ubuntu version higher.

curl -s https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.deb.sh | sudo bash
sudo apt-get install gitlab-ce=9.2.5-ce.0

https://packages.gitlab.com/gitlab/gitlab-ce/packages/ubuntu/xenial/gitlab-ce_9.2.5-ce.0_amd64.deb

or trusty (1 ubuntu version lower). Its been suggested that trusty has higher compatibility so you can try that first. But I agree that you should release-upgrade to ubuntu 16.04

https://packages.gitlab.com/gitlab/gitlab-ce/packages/ubuntu/trusty/gitlab-ce_9.0.10-ce.0_amd64.deb

curl -s https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.deb.sh | sudo bash
sudo apt-get install gitlab-ce=9.0.10-ce.0


问:
python: loop array in stats.anova
I have the following line:

```<code>print(sm.stats.anova_lm(fitModelDict['1'], fitModelDict['2'], fitModelDict['3'], type=1))
</code>```

I would like to know how the line can be written with a loop if I have:

```<code> fitModelDict[i],i=10
</code>```

Thank you.

答:
You can't. The closest to what you are wanting in python will be using argument unpacking:

```<code>some_args = ['one', 'two', 'three']
my_function(*some_args)

# equivalent to:
my_function(some_args[0], some_args[1], some_args[2])
</code>```

Or if the function can take keyword arguments, you can unpack dictionaries:

```<code>a = {'one':'1', 'two':'2', 'three':'3'}
my_function(**a)

# equivalent to:
my_function(one=1, two=2, three=3)
</code>```

So, in your case, you could use a loop before the function call to build up a list of the arguments you want to use, and then use argument unpacking as above.

Title: python: loop array in stats.anova

Body:
I have the following line:

print(sm.stats.anova_lm(fitModelDict['1'], fitModelDict['2'], fitModelDict['3'], type=1))

I would like to know how the line can be written with a loop if I have:

 fitModelDict[i],i=10

Thank you.

Body:
You can't. The closest to what you are wanting in python will be using argument unpacking:

some_args = ['one', 'two', 'three']
my_function(*some_args)

# equivalent to:
my_function(some_args[0], some_args[1], some_args[2])

Or if the function can take keyword arguments, you can unpack dictionaries:

a = {'one':'1', 'two':'2', 'three':'3'}
my_function(**a)

# equivalent to:
my_function(one=1, two=2, three=3)

So, in your case, you could use a loop before the function call to build up a list of the arguments you want to use, and then use argument unpacking as above.


问:
Java - parse xml string with variable tagnames?
I'm trying to parse an XML string, and the tagnames are variable; I haven't seen any examples on how to pull the information out without knowing them.  For example, I will always know the <response> and <data> tags below, but what falls inside/outside of them could be anything from <employee> to you name it.

```<code>    <?xml version="1.0" encoding="UTF-8"?>

     <response>
        <generic>
           ....
        </generic>
        <data>
             <employee>
                <name>Seagull</name>
                <id>3674</id>
                <age>34</age>
             </employee>
             <employee>
                <name>Robin</name>
                <id>3675</id>
                <age>25</age>
             </employee>
       </data>
   </response>
</code>```

答:
You could parse it into a generic dom object and traverse it. For example, you could use dom4j to do this.

From the dom4j quick start guide:

```<code>public void treeWalk(Document document) {
    treeWalk( document.getRootElement() );
}

public void treeWalk(Element element) {
    for ( int i = 0, size = element.nodeCount(); i < size; i++ ) {
        Node node = element.node(i);
        if ( node instanceof Element ) {
            treeWalk( (Element) node );
        }
        else {
            // do something....
        }
    }
}

public Document parse(URL url) throws DocumentException {
    SAXReader reader = new SAXReader();
    Document document = reader.read(url);
    return document;
}
</code>```

Body:
I'm trying to parse an XML string, and the tagnames are variable; I haven't seen any examples on how to pull the information out without knowing them.  For example, I will always know the <response> and <data> tags below, but what falls inside/outside of them could be anything from <employee> to you name it.

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

     <response>
        <generic>
           ....
        </generic>
        <data>
             <employee>
                <name>Seagull</name>
                <id>3674</id>
                <age>34</age>
             </employee>
             <employee>
                <name>Robin</name>
                <id>3675</id>
                <age>25</age>
             </employee>
       </data>
   </response>

Body:
You could parse it into a generic dom object and traverse it. For example, you could use dom4j to do this.

From the dom4j quick start guide:

public void treeWalk(Document document) {
    treeWalk( document.getRootElement() );
}

public void treeWalk(Element element) {
    for ( int i = 0, size = element.nodeCount(); i < size; i++ ) {
        Node node = element.node(i);
        if ( node instanceof Element ) {
            treeWalk( (Element) node );
        }
        else {
            // do something....
        }
    }
}

public Document parse(URL url) throws DocumentException {
    SAXReader reader = new SAXReader();
    Document document = reader.read(url);
    return document;
}


问:
Why am I getting a TokenMismatchException with Laravel and JQuery Sortable?
Update
I've changed the question slightly based on answers I've been given

I'm trying to save an order of rows, after the user manipulates the table via JQuery's Sortable Library.

```<code><div class="nametag-layout">
        <table class="table table-striped pagin-table table-bordered">
            <thead>
                <tr>
                    <td>Duration</td>
                    <td>Intent</td>
                    <td>Module</td>
                    <td>Outputs</td>
                    <td>Inputs</td>
                    <td>Logistics</td>
                </tr>
            </thead>
            <tbody>
            @foreach($mods as $key => $value)
                <tr class="table-tr draggable" data-id="{!!$value->id!!}">
                    <td>{{ $value->mod_duration }}</td>
                    <td>{{ $value->mod_intent }}</td>
                    <td>{{ $value->mod_module }}</td>
                    <td>{{ $value->mod_output }}</td>
                    <td>{{ $value->mod_input }}</td>
                    <td>{{ $value->mod_logistics }}</td>
                    <td>
                        <a class="btn btn-small btn-info" style="margin:auto; display:block;" href="{{ URL::to('mods/' . $value->id . '/edit') }}">Edit</a>
                    </td>
                </tr>
            @endforeach
            </tbody>
        </table>
    </div>
</code>```

After the table is manipulated, a js function takes the new order of the rows and passes it via a call.

```<code>$( "tbody" ).sortable({
                    stop: function (event, ui) {
                        var ids = new Array();
                        $('tr', this).each(function () {
                            ids.push($(this).data('id'));
                        });
                        $.get(window.location.href.split('?')[0] + "/sort", {ids: ids});
                    }
            });
</code>```

And a sort function in my controllers takes those values and parses them, then saves it to the DB so the new order is saved.

```<code>public function sort()
{
        $ids = request()->get('ids');
        if ($ids != null) {
            foreach ($ids as $i => $id) {
                $value = Mod::find($id);
                $value->sort = $i;
                $value->save();
            }
        }
}
</code>```

Every time I refresh the page, it doesn't save the order which I've moved the rows into. Checking chrome inspector and checking the XHR filter shows that every time I move a row, the sort function fires off, but every time it does fire off, a 'TokenMismatchException in VerifyCsrfToken' error occurs. I'm assuming either the js function isn't actually passing the values across to the controller, or I've messed up the call.

I've also added '/sort' to the $except parameter in 'VerifyCsrfToken.php', to temporarily fix the csrf issue I'm getting.

My route looks like this:

Route::get('/sort',array('as'=>'strawdog.sort','uses'=>'StrawdogController@sort'));

When I've done all this, the ajax call is sending the data to the controller, after checking using the XHR filter on chrome inspector, but whenever the rows are refreshed, it goes back to the original order of the rows instead of the manipulated order.

Basically, what am I doing wrong?

Things I've tried:

I've tried changing my js function to match the controller (post/get):

```<code>$.post(window.location.href.split('?')[0] + "/sort", {ids: ids});

public function sort()
{
        $ids = request()->post('ids');
...
</code>```

Changing both to the 'get' parameter just causes it to call another function I've written. Changing both to the 'post' parameter just returns the 'TokenMismatchException' error again.

I've tried another option, where I've changed the js function to 'get':

```<code>$.get(window.location.href.split('?')[0] + "/sort", {ids: ids});
</code>```

and the function to get as well:

```<code>$ids = request()->get('ids');
</code>```

and removed the function that conflicted with the get parameter. Then I've written a show function which handles to redirect to '/sort'.

```<code>public function show()
{
    return redirect('/sort');
}
</code>```

Going back to the chrome inspector and checking the XHR filter shows that it is passing the values across, but the sort function returns a 'NotFoundHttpException in RouteCollection.php line 179' error.

For reference, my route looks like this:
  Route::get('strawdog/sort',array('as'=>'strawdog.sort','uses'=>'StrawdogController@sort'));

答:
The Laravel framework has csrf protection.see https://laravel.com/docs/5.4/csrf.

You can add

```<code>var token = '{{csrf_token()}}';
$.post(window.location.href.split('?')[0] + "/sort", {ids: ids,_token:token});
</code>```

in your ajax data or see the solution in Laravel docs

Body:
Update
I've changed the question slightly based on answers I've been given

I'm trying to save an order of rows, after the user manipulates the table via JQuery's Sortable Library.

                    Duration
                    Intent
                    Module
                    Outputs
                    Inputs
                    Logistics

            @foreach($mods as $key => $value)

id!!}">
                    {{ $value->mod_duration }}
                    {{ $value->mod_intent }}
                    {{ $value->mod_module }}
                    {{ $value->mod_output }}
                    {{ $value->mod_input }}
                    {{ $value->mod_logistics }}

                        id . '/edit') }}">Edit

            @endforeach

After the table is manipulated, a js function takes the new order of the rows and passes it via a call.

$( "tbody" ).sortable({
                    stop: function (event, ui) {
                        var ids = new Array();
                        $('tr', this).each(function () {
                            ids.push($(this).data('id'));
                        });
                        $.get(window.location.href.split('?')[0] + "/sort", {ids: ids});
                    }
            });

And a sort function in my controllers takes those values and parses them, then saves it to the DB so the new order is saved.

public function sort()
{
        $ids = request()->get('ids');
        if ($ids != null) {
            foreach ($ids as $i => $id) {
                $value = Mod::find($id);
                $value->sort = $i;
                $value->save();
            }
        }
}

Every time I refresh the page, it doesn't save the order which I've moved the rows into. Checking chrome inspector and checking the XHR filter shows that every time I move a row, the sort function fires off, but every time it does fire off, a 'TokenMismatchException in VerifyCsrfToken' error occurs. I'm assuming either the js function isn't actually passing the values across to the controller, or I've messed up the call.

I've also added '/sort' to the $except parameter in 'VerifyCsrfToken.php', to temporarily fix the csrf issue I'm getting.

My route looks like this:

Route::get('/sort',array('as'=>'strawdog.sort','uses'=>'StrawdogController@sort'));

When I've done all this, the ajax call is sending the data to the controller, after checking using the XHR filter on chrome inspector, but whenever the rows are refreshed, it goes back to the original order of the rows instead of the manipulated order.

Basically, what am I doing wrong?

Things I've tried:

I've tried changing my js function to match the controller (post/get):

$.post(window.location.href.split('?')[0] + "/sort", {ids: ids});

public function sort()
{
        $ids = request()->post('ids');
...

Changing both to the 'get' parameter just causes it to call another function I've written. Changing both to the 'post' parameter just returns the 'TokenMismatchException' error again.

I've tried another option, where I've changed the js function to 'get':

$.get(window.location.href.split('?')[0] + "/sort", {ids: ids});

and the function to get as well:

$ids = request()->get('ids');

and removed the function that conflicted with the get parameter. Then I've written a show function which handles to redirect to '/sort'.

public function show()
{
    return redirect('/sort');
}

Going back to the chrome inspector and checking the XHR filter shows that it is passing the values across, but the sort function returns a 'NotFoundHttpException in RouteCollection.php line 179' error.

For reference, my route looks like this:
  Route::get('strawdog/sort',array('as'=>'strawdog.sort','uses'=>'StrawdogController@sort'));

Body:
The Laravel framework has csrf protection.see https://laravel.com/docs/5.4/csrf.

You can add

var token = '{{csrf_token()}}';
$.post(window.location.href.split('?')[0] + "/sort", {ids: ids,_token:token});

in your ajax data or see the solution in Laravel docs


问:
Make 3D object illuminate differently over time in JavaFX
Need to make a sphere in JavaFX "blink" over time, like fade in and fade out. Is it possible? Or at least change shades of color. I managed to make it blink by changing SelfIlluminationMap property of the PhongMaterial I am using, with this code

```<code>import javafx.animation.*;
import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.image.Image;
import javafx.scene.paint.*;
import javafx.scene.shape.*;
import javafx.scene.transform.*;
import javafx.stage.Stage;
import javafx.util.Duration;

public class JavaFXApplication15 extends Application {

    Image im = new Image("bump.jpg");
    PhongMaterial ph = new PhongMaterial(Color.GREEN);
    int nums = 0;

    UpdateTimer timer;

    private class UpdateTimer extends AnimationTimer {

        int counter = 0;

        @Override
        public void handle(long now) {
            if (counter == 20) {
                update();
                counter = 0;
            }
            counter++;

        }
    }

    private Parent createContent() throws Exception {

        timer = new UpdateTimer();
        ph = new PhongMaterial(Color.YELLOW, null, null, null, im);

        Box box = new Box(5, 5, 5);
        box.setMaterial(ph);

        // Create and position camera
        PerspectiveCamera camera = new PerspectiveCamera(true);
        camera.getTransforms().addAll(
                new Rotate(-20, Rotate.X_AXIS),
                new Translate(0, 0, -50)
        );

        // Build the Scene Graph
        Group root = new Group();
        root.getChildren().add(camera);
        root.getChildren().add(box);

        // Use a SubScene
        SubScene subScene = new SubScene(
                root,
                300, 300,
                true,
                SceneAntialiasing.BALANCED
        );
        subScene.setFill(Color.ALICEBLUE);
        subScene.setCamera(camera);
        Group group = new Group();
        group.getChildren().add(subScene);

        return group;
    }

    void update() {

        if (ph.getSelfIlluminationMap() != null) {
            ph.setSelfIlluminationMap(null);
        } else {
            ph.setSelfIlluminationMap(im);
        }

    }

    @Override
    public void start(Stage stage) throws Exception {
        stage.setResizable(false);
        Scene scene = new Scene(createContent());
        stage.setScene(scene);
        stage.show();
        timer.start();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

but is it possible to make it fade in and out? With some kind of transition possibly?

答:
Just to see the effect, I tried animating the specularColor of a sphere's PhongMaterial. Starting from this example, I followed the approach shown here to get a color lookup table of equally spaced brightness values of a given hue.

```<code>private final Queue<Color> clut = new LinkedList<>();
</code>```

The implementation of handle() simply cycles through the table.

```<code>@Override
public void handle(long now) {
    redMaterial.setSpecularColor(clut.peek());
    clut.add(clut.remove());
}
</code>```

If the result is appealing, a more flexible approach might accrue from using a concrete subclass of Transition.

```<code>private final Animation animation = new Transition() {

     {
         setCycleDuration(Duration.millis(1000));
         setAutoReverse(true);
         setCycleCount(INDEFINITE);
     }

     @Override
     protected void interpolate(double d) {
         redMaterial.setSpecularColor(Color.hsb(LITE.getHue(), 1, d));
         redMaterial.setDiffuseColor(Color.hsb(DARK.getHue(), 1, d / 2));
     }
 };
</code>```

```<code>import java.util.LinkedList;
import java.util.Queue;
import javafx.animation.AnimationTimer;
import javafx.animation.Animation;
import javafx.animation.Transition;
import javafx.application.Application;
import javafx.geometry.Point3D;
import javafx.scene.Group;
import javafx.scene.PerspectiveCamera;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.ScrollEvent;
import javafx.scene.paint.Color;
import javafx.scene.paint.PhongMaterial;
import javafx.scene.shape.Box;
import javafx.scene.shape.DrawMode;
import javafx.scene.shape.Sphere;
import javafx.scene.transform.Rotate;
import javafx.scene.transform.Transform;
import javafx.stage.Stage;
import javafx.util.Duration;

/**
 * @see https://stackoverflow.com/a/44447913/230513
 * @see https://stackoverflow.com/a/37755149/230513
 * @see https://stackoverflow.com/a/37743539/230513
 * @see https://stackoverflow.com/a/37370840/230513
 */
public class TriadBox extends Application {

    private static final double SIZE = 300;
    private final Content content = Content.create(SIZE);
    private double mousePosX, mousePosY, mouseOldX, mouseOldY, mouseDeltaX, mouseDeltaY;

    private static final class Content {

        private static final double WIDTH = 3;
        private static final Color LITE = Color.RED;
        private static final Color DARK = Color.RED.darker().darker();
        private final Xform group = new Xform();
        private final Group cube = new Group();
        private final Group axes = new Group();
        private final Box xAxis;
        private final Box yAxis;
        private final Box zAxis;
        private final Box box;
        private final Sphere sphere;
        private final PhongMaterial redMaterial = new PhongMaterial();
        private final UpdateTimer timer = new UpdateTimer();

        private class UpdateTimer extends AnimationTimer {
            private static final double N = 32d;
            private final Queue<Color> clut = new LinkedList<>();

            public UpdateTimer() {
                for (int i = 0; i < N; i++) {
                    clut.add(Color.hsb(LITE.getHue(), 1, 1 - (i / N)));
                }
                for (int i = 0; i < N; i++) {
                    clut.add(Color.hsb(LITE.getHue(), 1, i / N));
                }
            }

            @Override
            public void handle(long now) {
                redMaterial.setSpecularColor(clut.peek());
                clut.add(clut.remove());
            }
        }

        private final Animation animation = new Transition() {

             {
                 setCycleDuration(Duration.millis(1000));
                 setAutoReverse(true);
                 setCycleCount(INDEFINITE);
             }

             @Override
             protected void interpolate(double d) {
                 redMaterial.setSpecularColor(Color.hsb(LITE.getHue(), 1, d));
                 redMaterial.setDiffuseColor(Color.hsb(DARK.getHue(), 1, d / 2));
             }
         };

        private static Content create(double size) {
            Content c = new Content(size);
            c.cube.getChildren().addAll(c.box, c.sphere);
            c.axes.getChildren().addAll(c.xAxis, c.yAxis, c.zAxis);
            c.group.getChildren().addAll(c.cube, c.axes);
            return c;
        }

        private Content(double size) {
            double edge = 3 * size / 4;
            xAxis = createBox(edge, WIDTH, WIDTH, edge);
            yAxis = createBox(WIDTH, edge / 2, WIDTH, edge);
            zAxis = createBox(WIDTH, WIDTH, edge / 4, edge);
            box = new Box(edge, edge / 2, edge / 4);
            box.setDrawMode(DrawMode.LINE);
            sphere = new Sphere(8);
            redMaterial.setDiffuseColor(DARK);
            redMaterial.setSpecularColor(LITE);
            sphere.setMaterial(redMaterial);
            sphere.setTranslateX(edge / 2);
            sphere.setTranslateY(-edge / 4);
            sphere.setTranslateZ(-edge / 8);
        }

        private Box createBox(double w, double h, double d, double edge) {
            Box b = new Box(w, h, d);
            b.setMaterial(new PhongMaterial(Color.AQUA));
            b.setTranslateX(-edge / 2 + w / 2);
            b.setTranslateY(edge / 4 - h / 2);
            b.setTranslateZ(edge / 8 - d / 2);
            return b;
        }
    }

    private static class Xform extends Group {

        private final Point3D px = new Point3D(1.0, 0.0, 0.0);
        private final Point3D py = new Point3D(0.0, 1.0, 0.0);
        private Rotate r;
        private Transform t = new Rotate();

        public void rx(double angle) {
            r = new Rotate(angle, px);
            this.t = t.createConcatenation(r);
            this.getTransforms().clear();
            this.getTransforms().addAll(t);
        }

        public void ry(double angle) {
            r = new Rotate(angle, py);
            this.t = t.createConcatenation(r);
            this.getTransforms().clear();
            this.getTransforms().addAll(t);
        }

        public void rz(double angle) {
            r = new Rotate(angle);
            this.t = t.createConcatenation(r);
            this.getTransforms().clear();
            this.getTransforms().addAll(t);
        }
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setTitle("JavaFX 3D");
        Scene scene = new Scene(content.group, SIZE * 2, SIZE * 2, true);
        primaryStage.setScene(scene);
        scene.setFill(Color.BLACK);
        PerspectiveCamera camera = new PerspectiveCamera(true);
        camera.setFarClip(SIZE * 6);
        camera.setTranslateZ(-2 * SIZE);
        scene.setCamera(camera);
        scene.setOnMousePressed((MouseEvent e) -> {
            mousePosX = e.getSceneX();
            mousePosY = e.getSceneY();
            mouseOldX = e.getSceneX();
            mouseOldY = e.getSceneY();
        });
        scene.setOnMouseDragged((MouseEvent e) -> {
            mouseOldX = mousePosX;
            mouseOldY = mousePosY;
            mousePosX = e.getSceneX();
            mousePosY = e.getSceneY();
            mouseDeltaX = (mousePosX - mouseOldX);
            mouseDeltaY = (mousePosY - mouseOldY);
            if (e.isShiftDown()) {
                content.group.rz(-mouseDeltaX * 180.0 / scene.getWidth());
            } else if (e.isPrimaryButtonDown()) {
                content.group.rx(+mouseDeltaY * 180.0 / scene.getHeight());
                content.group.ry(-mouseDeltaX * 180.0 / scene.getWidth());
            } else if (e.isSecondaryButtonDown()) {
                camera.setTranslateX(camera.getTranslateX() - mouseDeltaX * 0.1);
                camera.setTranslateY(camera.getTranslateY() - mouseDeltaY * 0.1);
            }
        });
        scene.setOnScroll((final ScrollEvent e) -> {
            camera.setTranslateZ(camera.getTranslateZ() + e.getDeltaY());
        });
        primaryStage.show();
        //content.timer.start();
        content.animation.play();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

Body:
Need to make a sphere in JavaFX "blink" over time, like fade in and fade out. Is it possible? Or at least change shades of color. I managed to make it blink by changing SelfIlluminationMap property of the PhongMaterial I am using, with this code

import javafx.animation.*;
import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.image.Image;
import javafx.scene.paint.*;
import javafx.scene.shape.*;
import javafx.scene.transform.*;
import javafx.stage.Stage;
import javafx.util.Duration;

public class JavaFXApplication15 extends Application {

    Image im = new Image("bump.jpg");
    PhongMaterial ph = new PhongMaterial(Color.GREEN);
    int nums = 0;

    UpdateTimer timer;

    private class UpdateTimer extends AnimationTimer {

        int counter = 0;

        @Override
        public void handle(long now) {
            if (counter == 20) {
                update();
                counter = 0;
            }
            counter++;

        }
    }

    private Parent createContent() throws Exception {

        timer = new UpdateTimer();
        ph = new PhongMaterial(Color.YELLOW, null, null, null, im);

        Box box = new Box(5, 5, 5);
        box.setMaterial(ph);

        // Create and position camera
        PerspectiveCamera camera = new PerspectiveCamera(true);
        camera.getTransforms().addAll(
                new Rotate(-20, Rotate.X_AXIS),
                new Translate(0, 0, -50)
        );

        // Build the Scene Graph
        Group root = new Group();
        root.getChildren().add(camera);
        root.getChildren().add(box);

        // Use a SubScene
        SubScene subScene = new SubScene(
                root,
                300, 300,
                true,
                SceneAntialiasing.BALANCED
        );
        subScene.setFill(Color.ALICEBLUE);
        subScene.setCamera(camera);
        Group group = new Group();
        group.getChildren().add(subScene);

        return group;
    }

    void update() {

        if (ph.getSelfIlluminationMap() != null) {
            ph.setSelfIlluminationMap(null);
        } else {
            ph.setSelfIlluminationMap(im);
        }

    }

    @Override
    public void start(Stage stage) throws Exception {
        stage.setResizable(false);
        Scene scene = new Scene(createContent());
        stage.setScene(scene);
        stage.show();
        timer.start();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

but is it possible to make it fade in and out? With some kind of transition possibly?

Body:
Just to see the effect, I tried animating the specularColor of a sphere's PhongMaterial. Starting from this example, I followed the approach shown here to get a color lookup table of equally spaced brightness values of a given hue.

private final Queue<Color> clut = new LinkedList<>();

The implementation of handle() simply cycles through the table.

@Override
public void handle(long now) {
    redMaterial.setSpecularColor(clut.peek());
    clut.add(clut.remove());
}

If the result is appealing, a more flexible approach might accrue from using a concrete subclass of Transition.

private final Animation animation = new Transition() {

     {
         setCycleDuration(Duration.millis(1000));
         setAutoReverse(true);
         setCycleCount(INDEFINITE);
     }

     @Override
     protected void interpolate(double d) {
         redMaterial.setSpecularColor(Color.hsb(LITE.getHue(), 1, d));
         redMaterial.setDiffuseColor(Color.hsb(DARK.getHue(), 1, d / 2));
     }
 };

import java.util.LinkedList;
import java.util.Queue;
import javafx.animation.AnimationTimer;
import javafx.animation.Animation;
import javafx.animation.Transition;
import javafx.application.Application;
import javafx.geometry.Point3D;
import javafx.scene.Group;
import javafx.scene.PerspectiveCamera;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.ScrollEvent;
import javafx.scene.paint.Color;
import javafx.scene.paint.PhongMaterial;
import javafx.scene.shape.Box;
import javafx.scene.shape.DrawMode;
import javafx.scene.shape.Sphere;
import javafx.scene.transform.Rotate;
import javafx.scene.transform.Transform;
import javafx.stage.Stage;
import javafx.util.Duration;

/**
 * @see https://stackoverflow.com/a/44447913/230513
 * @see https://stackoverflow.com/a/37755149/230513
 * @see https://stackoverflow.com/a/37743539/230513
 * @see https://stackoverflow.com/a/37370840/230513
 */
public class TriadBox extends Application {

    private static final double SIZE = 300;
    private final Content content = Content.create(SIZE);
    private double mousePosX, mousePosY, mouseOldX, mouseOldY, mouseDeltaX, mouseDeltaY;

    private static final class Content {

        private static final double WIDTH = 3;
        private static final Color LITE = Color.RED;
        private static final Color DARK = Color.RED.darker().darker();
        private final Xform group = new Xform();
        private final Group cube = new Group();
        private final Group axes = new Group();
        private final Box xAxis;
        private final Box yAxis;
        private final Box zAxis;
        private final Box box;
        private final Sphere sphere;
        private final PhongMaterial redMaterial = new PhongMaterial();
        private final UpdateTimer timer = new UpdateTimer();

        private class UpdateTimer extends AnimationTimer {
            private static final double N = 32d;
            private final Queue<Color> clut = new LinkedList<>();

            public UpdateTimer() {
                for (int i = 0; i < N; i++) {
                    clut.add(Color.hsb(LITE.getHue(), 1, 1 - (i / N)));
                }
                for (int i = 0; i < N; i++) {
                    clut.add(Color.hsb(LITE.getHue(), 1, i / N));
                }
            }

            @Override
            public void handle(long now) {
                redMaterial.setSpecularColor(clut.peek());
                clut.add(clut.remove());
            }
        }

        private final Animation animation = new Transition() {

             {
                 setCycleDuration(Duration.millis(1000));
                 setAutoReverse(true);
                 setCycleCount(INDEFINITE);
             }

             @Override
             protected void interpolate(double d) {
                 redMaterial.setSpecularColor(Color.hsb(LITE.getHue(), 1, d));
                 redMaterial.setDiffuseColor(Color.hsb(DARK.getHue(), 1, d / 2));
             }
         };

        private static Content create(double size) {
            Content c = new Content(size);
            c.cube.getChildren().addAll(c.box, c.sphere);
            c.axes.getChildren().addAll(c.xAxis, c.yAxis, c.zAxis);
            c.group.getChildren().addAll(c.cube, c.axes);
            return c;
        }

        private Content(double size) {
            double edge = 3 * size / 4;
            xAxis = createBox(edge, WIDTH, WIDTH, edge);
            yAxis = createBox(WIDTH, edge / 2, WIDTH, edge);
            zAxis = createBox(WIDTH, WIDTH, edge / 4, edge);
            box = new Box(edge, edge / 2, edge / 4);
            box.setDrawMode(DrawMode.LINE);
            sphere = new Sphere(8);
            redMaterial.setDiffuseColor(DARK);
            redMaterial.setSpecularColor(LITE);
            sphere.setMaterial(redMaterial);
            sphere.setTranslateX(edge / 2);
            sphere.setTranslateY(-edge / 4);
            sphere.setTranslateZ(-edge / 8);
        }

        private Box createBox(double w, double h, double d, double edge) {
            Box b = new Box(w, h, d);
            b.setMaterial(new PhongMaterial(Color.AQUA));
            b.setTranslateX(-edge / 2 + w / 2);
            b.setTranslateY(edge / 4 - h / 2);
            b.setTranslateZ(edge / 8 - d / 2);
            return b;
        }
    }

    private static class Xform extends Group {

        private final Point3D px = new Point3D(1.0, 0.0, 0.0);
        private final Point3D py = new Point3D(0.0, 1.0, 0.0);
        private Rotate r;
        private Transform t = new Rotate();

        public void rx(double angle) {
            r = new Rotate(angle, px);
            this.t = t.createConcatenation(r);
            this.getTransforms().clear();
            this.getTransforms().addAll(t);
        }

        public void ry(double angle) {
            r = new Rotate(angle, py);
            this.t = t.createConcatenation(r);
            this.getTransforms().clear();
            this.getTransforms().addAll(t);
        }

        public void rz(double angle) {
            r = new Rotate(angle);
            this.t = t.createConcatenation(r);
            this.getTransforms().clear();
            this.getTransforms().addAll(t);
        }
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setTitle("JavaFX 3D");
        Scene scene = new Scene(content.group, SIZE * 2, SIZE * 2, true);
        primaryStage.setScene(scene);
        scene.setFill(Color.BLACK);
        PerspectiveCamera camera = new PerspectiveCamera(true);
        camera.setFarClip(SIZE * 6);
        camera.setTranslateZ(-2 * SIZE);
        scene.setCamera(camera);
        scene.setOnMousePressed((MouseEvent e) -> {
            mousePosX = e.getSceneX();
            mousePosY = e.getSceneY();
            mouseOldX = e.getSceneX();
            mouseOldY = e.getSceneY();
        });
        scene.setOnMouseDragged((MouseEvent e) -> {
            mouseOldX = mousePosX;
            mouseOldY = mousePosY;
            mousePosX = e.getSceneX();
            mousePosY = e.getSceneY();
            mouseDeltaX = (mousePosX - mouseOldX);
            mouseDeltaY = (mousePosY - mouseOldY);
            if (e.isShiftDown()) {
                content.group.rz(-mouseDeltaX * 180.0 / scene.getWidth());
            } else if (e.isPrimaryButtonDown()) {
                content.group.rx(+mouseDeltaY * 180.0 / scene.getHeight());
                content.group.ry(-mouseDeltaX * 180.0 / scene.getWidth());
            } else if (e.isSecondaryButtonDown()) {
                camera.setTranslateX(camera.getTranslateX() - mouseDeltaX * 0.1);
                camera.setTranslateY(camera.getTranslateY() - mouseDeltaY * 0.1);
            }
        });
        scene.setOnScroll((final ScrollEvent e) -> {
            camera.setTranslateZ(camera.getTranslateZ() + e.getDeltaY());
        });
        primaryStage.show();
        //content.timer.start();
        content.animation.play();
    }

    public static void main(String[] args) {
        launch(args);
    }
}


问:
Why Vue.js needs to be add in the body tag
I added my vue.js in the header but it has an error that says element root can't be found, because I have a div with an id of root.

But when I add it on the body everything works fine.

This is my js code.

```<code>new Vue({
     el: '#root'
});
</code>```

And this is my html.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

    <task-list>

    </task-list>

```

答:
Hi I didn't see any included js(except for vue package) in your html. But I think the solution is to place your script in footer.

Also if that doesnt work place it inside window.onload

```<code>window.onload = function() {
    new Vue({
        el: '#root'
    });
};
</code>```

Body:
I added my vue.js in the header but it has an error that says element root can't be found, because I have a div with an id of root.

But when I add it on the body everything works fine.

This is my js code.

new Vue({
     el: '#root'
});

And this is my html.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

    <task-list>

    </task-list>

Body:
Hi I didn't see any included js(except for vue package) in your html. But I think the solution is to place your script in footer.

Also if that doesnt work place it inside window.onload

window.onload = function() {
    new Vue({
        el: '#root'
    });
};


问:
d3 chord: center text on circle
I use the d3 chord diagram example of Andrew and want to center all text labels within the curved slice. I tried many things but was never able to center the texts. Do you know what wizzard trick there is needed?

```<code>var width = 720,
height = 720,
outerRadius = Math.min(width, height) / 2 - 10,
innerRadius = outerRadius - 24;

var formatPercent = d3.format(".1%");

var arc = d3.svg.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius);

var layout = d3.layout.chord()
.padding(.04)
.sortSubgroups(d3.descending)
.sortChords(d3.ascending);

var path = d3.svg.chord()
.radius(innerRadius);

var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("id", "circle")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

svg.append("circle")
.attr("r", outerRadius);

d3.csv("ex_csv.csv", function(cities) {
d3.json("ex_json.json", function(matrix) {

// Compute the chord layout.
layout.matrix(matrix);

// Add a group per neighborhood.
var group = svg.selectAll(".group")
.data(layout.groups)
.enter().append("g")
.attr("class", "group")
.on("mouseover", mouseover);

// Add the group arc.
var groupPath = group.append("path")
.attr("id", function(d, i) { return "group" + i; })
.attr("d", arc)
.style("fill", function(d, i) { return cities[i].color; });

// Add a text label.
var groupText = group.append("text")
.attr("x", 6)
.attr("dy", 15);

groupText.append("textPath")
.attr("xlink:href", function(d, i) { return "#group" + i; })
.text(function(d, i) { return cities[i].name; });

// Remove the labels that don't fit. :(
groupText.filter(function(d, i) { return groupPath[0][i].getTotalLength() / 2 - 16 < this.getComputedTextLength(); })
.remove();

// Add the chords.
var chord = svg.selectAll(".chord")
.data(layout.chords)
.enter().append("path")
.attr("class", "chord")
.style("fill", function(d) { return cities[d.source.index].color; })
.attr("d", path);

}
});
});

</script>
</code>```

答:
As an aside, I would suggest looking to upgrade to v4, documentation for v2 is nearly non-existent and is very hard to help with.

You can set both the text-anchor and the  startOffset property to achieve what you are looking for.

First, you'll want to set text-anchor to middle as it is easier to specify the middle point than to find the middle point and work back to find where the text should start.

Second you'll need to set a startOffset. Note that if you use 50%, the text will not appear where you want, as the total length of the text path is all sides of the closed loop (chord anchor) you are appending to. Setting it to 25 % would work if you did not have a different outer and inner radius. But, as you have an outer radius that is 24 pixels greater than the inner radius you can try something like this to calculate the number of pixels you need to offset the center of the text:

```<code>groupText.append("textPath")
.attr("xlink:href", function(d, i) { return "#group" + i; })
.text(function(d, i) { return cities[i].name; })
.attr("startOffset",function(d,i) { return (groupPath[0][i].getTotalLength() - 48) / 4 })
.style("text-anchor","middle");
</code>```

I subtract 48 because the sides of the anchor are 24 pixels each (the difference in the radii). I divide by four because the path doubles back on itself. If it was a general line I would just divide by two.

This approach is a little simplistic as the outer circumference is not the same as the inner circumference of each chord anchor, so I am off by a little bit, but it should be workable.

For labels that are on the cusp of being displayed, this will be awkward: the inner radius is shorter, so the formula for deteriming if a string is short enough to be displayed may be wrong - which may lead to some characters climbing up the side of the anchor (your example also 16 pixels as the difference in radii to calculate if text is too long, rather than 24).

This is the end result:

Here is a demonstration.

Title: d3 chord: center text on circle

Body:
I use the d3 chord diagram example of Andrew and want to center all text labels within the curved slice. I tried many things but was never able to center the texts. Do you know what wizzard trick there is needed?

var width = 720,
height = 720,
outerRadius = Math.min(width, height) / 2 - 10,
innerRadius = outerRadius - 24;

var formatPercent = d3.format(".1%");

var arc = d3.svg.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius);

var layout = d3.layout.chord()
.padding(.04)
.sortSubgroups(d3.descending)
.sortChords(d3.ascending);

var path = d3.svg.chord()
.radius(innerRadius);

var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("id", "circle")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

svg.append("circle")
.attr("r", outerRadius);

d3.csv("ex_csv.csv", function(cities) {
d3.json("ex_json.json", function(matrix) {

// Compute the chord layout.
layout.matrix(matrix);

// Add a group per neighborhood.
var group = svg.selectAll(".group")
.data(layout.groups)
.enter().append("g")
.attr("class", "group")
.on("mouseover", mouseover);

// Add the group arc.
var groupPath = group.append("path")
.attr("id", function(d, i) { return "group" + i; })
.attr("d", arc)
.style("fill", function(d, i) { return cities[i].color; });

// Add a text label.
var groupText = group.append("text")
.attr("x", 6)
.attr("dy", 15);

groupText.append("textPath")
.attr("xlink:href", function(d, i) { return "#group" + i; })
.text(function(d, i) { return cities[i].name; });

// Remove the labels that don't fit. :(
groupText.filter(function(d, i) { return groupPath[0][i].getTotalLength() / 2 - 16 < this.getComputedTextLength(); })
.remove();

// Add the chords.
var chord = svg.selectAll(".chord")
.data(layout.chords)
.enter().append("path")
.attr("class", "chord")
.style("fill", function(d) { return cities[d.source.index].color; })
.attr("d", path);

}
});
});

</script>

Body:
As an aside, I would suggest looking to upgrade to v4, documentation for v2 is nearly non-existent and is very hard to help with.

You can set both the text-anchor and the  startOffset property to achieve what you are looking for.

First, you'll want to set text-anchor to middle as it is easier to specify the middle point than to find the middle point and work back to find where the text should start.

Second you'll need to set a startOffset. Note that if you use 50%, the text will not appear where you want, as the total length of the text path is all sides of the closed loop (chord anchor) you are appending to. Setting it to 25 % would work if you did not have a different outer and inner radius. But, as you have an outer radius that is 24 pixels greater than the inner radius you can try something like this to calculate the number of pixels you need to offset the center of the text:

groupText.append("textPath")
.attr("xlink:href", function(d, i) { return "#group" + i; })
.text(function(d, i) { return cities[i].name; })
.attr("startOffset",function(d,i) { return (groupPath[0][i].getTotalLength() - 48) / 4 })
.style("text-anchor","middle");

I subtract 48 because the sides of the anchor are 24 pixels each (the difference in the radii). I divide by four because the path doubles back on itself. If it was a general line I would just divide by two.

This approach is a little simplistic as the outer circumference is not the same as the inner circumference of each chord anchor, so I am off by a little bit, but it should be workable.

For labels that are on the cusp of being displayed, this will be awkward: the inner radius is shorter, so the formula for deteriming if a string is short enough to be displayed may be wrong - which may lead to some characters climbing up the side of the anchor (your example also 16 pixels as the difference in radii to calculate if text is too long, rather than 24).

This is the end result:

Here is a demonstration.


问:
are PDO::prepare and PDO::quote completely secure?
i am using PDO package to manage my application database.
i use PDO::prepare , PDOStatement::execute and somtimes PDO::quote , PDO::query / PDO::exec to excute my queries

are PDO::prepare and PDO::quote completely secure? or shoud i make more work to properly validate my inputs.not only for databaase but for php code either
Thank you

答:
There's nothing magic about using prepare(). You can interpolate unsafe variables into a string and then prepare that string. Boom—SQL injection. Preparing a statement doesn't make it safe.

```<code>$stmt = $pdo->prepare("SELECT * FROM MyTable WHERE id = {$_POST['id']}"); // UNSAFE!
</code>```

What makes it safe is using parameters.

```<code>$stmt = $pdo->prepare("SELECT * FROM MyTable WHERE id = ?");
$stmt->execute([$_POST['id']]); // SAFE!
</code>```

Naturally, people say "use prepared statements" because you must use prepared statements to use parameters. But just saying "use prepared statements" kind of misses the point, and some developers get the wrong understanding.

The PDO quote() method is also safe, but I find it simpler and easier to use parameters.

```<code>$idQuoted = $pdo->quote($_POST['id']);
$stmt = $pdo->prepare("SELECT * FROM MyTable WHERE id = $idQuoted");
</code>```

Body:
There's nothing magic about using prepare(). You can interpolate unsafe variables into a string and then prepare that string. Boom—SQL injection. Preparing a statement doesn't make it safe.

$stmt = $pdo->prepare("SELECT * FROM MyTable WHERE id = {$_POST['id']}"); // UNSAFE!

What makes it safe is using parameters.

$stmt = $pdo->prepare("SELECT * FROM MyTable WHERE id = ?");
$stmt->execute([$_POST['id']]); // SAFE!

Naturally, people say "use prepared statements" because you must use prepared statements to use parameters. But just saying "use prepared statements" kind of misses the point, and some developers get the wrong understanding.

The PDO quote() method is also safe, but I find it simpler and easier to use parameters.

$idQuoted = $pdo->quote($_POST['id']);
$stmt = $pdo->prepare("SELECT * FROM MyTable WHERE id = $idQuoted");