答:
Now try this and u can see the demo here Demo

```<code> <!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>SlidesJS Standard Code Example</title>
  <meta name="description" content="SlidesJS is a simple slideshow plugin for jQuery. Packed with a useful set of features to help novice and advanced developers alike create elegant and user-friendly slideshows.">
  <meta name="author" content="Nathan Searles">

  <!-- SlidesJS Required (if responsive): Sets the page width to the device width. -->
  <meta name="viewport" content="width=device-width">
  <!-- End SlidesJS Required -->

  <!-- CSS for slidesjs.com example -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
  <!-- End CSS for slidesjs.com example -->

  <!-- SlidesJS Optional: If you'd like to use this design -->
  <style>
    body {
      -webkit-font-smoothing: antialiased;
      font: normal 15px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif;
      color: #232525;
    }

    #slides,
    #slides2,
    #slides3 {
      display: none;
      margin-bottom:50px;
    }

    .slidesjs-navigation {
      margin-top:3px;
    }

    .slidesjs-previous {
      margin-right: 5px;
      float: left;
    }

    .slidesjs-next {
      margin-right: 5px;
      float: left;
    }

    .slidesjs-pagination {
      margin: 6px 0 0;
      float: right;
      list-style: none;
    }

    .slidesjs-pagination li {
      float: left;
      margin: 0 1px;
    }

    .slidesjs-pagination li a {
      display: block;
      width: 13px;
      height: 0;
      padding-top: 13px;
      background-image: url("https://s16.postimg.org/pt4k43i9x/pagination.png");
      background-position: 0 0;
      float: left;
      overflow: hidden;
    }

    .slidesjs-pagination li a.active,
    .slidesjs-pagination li a:hover.active {
      background-position: 0 -13px
    }

    .slidesjs-pagination li a:hover {
      background-position: 0 -26px
    }
    .navbar {
      overflow: hidden
    }
  </style>
  <!-- End SlidesJS Optional-->

  <!-- SlidesJS Required: These styles are required if you'd like a responsive slideshow -->
  <style>
    #slides {
      display: none
    }

    .container {
      margin: 0 auto
    }

    /* For tablets & smart phones */

    /* For smartphones */

  </style>
  <!-- SlidesJS Required: -->
</head>
<body>
<div class="topnav">
   <img src="https://s4.postimg.org/ojd13poal/northman_wordmark_CMYK.png">
   <nav>
      <ul>
         <li class="dropdown">
            <a href="#"><b>INSURANCE</b> <i class="fa fa-angle-down"></i></a>
            <ul class="dropdown-content">
               <li><a href="#"><i>INDIVIDUAL</i></a>
               </li>
               <li><a href="#"><i>CORPORATE</i></a>
               </li>
            </ul>
         </li>
         <li class="our-story">OUR STORY</li>
         <li class="login-signup">Log In | Sign up</li>
         <li class="get-covered">GET <strong style="font-style:italic">COVERED</strong>
         </li>
      </ul>
   </nav>
</div>
  <!-- SlidesJS Required: Start Slides -->
  <!-- The container is used to define the width of the slideshow -->
  <div class="container">
   <h3>INSURANCE FORM</h3>
   <h4><i>BASIC DETAILS</i></h4>
   <br>
    <div id="slides" class="container-fluid" >

  <form action="/action_page.php" class="form-horizontal">

      <div class="form-group">
         <div class="col-sm-6">
            <label>FIRST NAME</label>
            <input type="text" class="form-control" name="fname" value="Mickey 1">
         </div>
         <div class="col-sm-6">
            <label>LAST NAME</label>
            <input type="text" class="form-control" name="lname" value="Mouse">
         </div>
      </div>
      <div class="form-group">
         <div class="col-sm-6">
            <label>EMAIL</label>
            <input type="text" class="form-control" name="email" value="abc@host.com">
         </div>
         <div class="col-sm-6">
            <label>PHONE NUMBER</label>
            <input type="text" class="form-control" name="number" value="123-456-789">
         </div>
      </div>
      <div class="form-group">
         <div class="col-sm-6">
            <label>COUNTRY</label>
            <select name="country" class="form-control">
               <option value="canada">Canada</option>
            </select>
         </div>
         <div class="col-sm-3">
            <label>PROVINCE</label>
            <select name="province" class="form-control">
               <option value="ontario">ONTARIO</option>
            </select>
         </div>
         <div class="col-sm-3">
            <label>CITY</label>
            <select name="city" class="form-control">
               <option value="ottawa">OTTAWA</option>
            </select>
         </div>
      </div>
   </form>
  <form action="/action_page.php" class="form-horizontal">
      <div class="form-group">
         <div class="col-sm-6">
            <label>FIRST NAME</label>
            <input type="text" class="form-control" name="fname" value="Mickey 2">
         </div>
         <div class="col-sm-6">
            <label>LAST NAME</label>
            <input type="text" class="form-control" name="lname" value="Mouse">
         </div>
      </div>
      <div class="form-group">
         <div class="col-sm-6">
            <label>EMAIL</label>
            <input type="text" class="form-control" name="email" value="abc@host.com">
         </div>
         <div class="col-sm-6">
            <label>PHONE NUMBER</label>
            <input type="text" class="form-control" name="number" value="123-456-789">
         </div>
      </div>
      <div class="form-group">
         <div class="col-sm-6">
            <label>COUNTRY</label>
            <select name="country" class="form-control">
               <option value="canada">Canada</option>
            </select>
         </div>
         <div class="col-sm-3">
            <label>PROVINCE</label>
            <select name="province" class="form-control">
               <option value="ontario">ONTARIO</option>
            </select>
         </div>
         <div class="col-sm-3">
            <label>CITY</label>
            <select name="city" class="form-control">
               <option value="ottawa">OTTAWA</option>
            </select>
         </div>
      </div>

   </form>

      <a href="#" class="slidesjs-previous slidesjs-navigation"><i class="icon-chevron-left"></i></a>
      <a href="#" class="slidesjs-next slidesjs-navigation"><i class="icon-chevron-right"></i></a>
    </div>
  </div>
  <!-- End SlidesJS Required: Start Slides -->

  <!-- SlidesJS Required: Link to jQuery -->
  <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
  <!-- End SlidesJS Required -->

  <!-- SlidesJS Required: Link to jquery.slides.js -->
  <script src="js/jquery.slides.min.js"></script>
  <!-- End SlidesJS Required -->

  <!-- SlidesJS Required: Initialize SlidesJS with a jQuery doc ready -->
  <script>
    $(function() {
      $('#slides').slidesjs({
        width: 800,
        height: 528,
        navigation: false
      });
      $('.form-horizontal').css('padding','0 45px 0 0')

      /*
        To have multiple slideshows on the same page
        they just need to have separate IDs
      */
      $('#slides2').slidesjs({
        width: 800,
        height: 528,
        navigation: false,
        start: 3,
        play: {
          auto: true
        }
      });

      $('#slides3').slidesjs({
        width: 800,
        height: 528,
        navigation: false
      });
    });
  </script>
  <!-- End SlidesJS Required -->
</body>
</html>
</code>```

and Style css

```<code>#slides {
  position: relative;
}
#slides .slidesjs-pagination {
  position: absolute;
  top: 11%; right: 0;
  transform: translateY(-50%);
  z-index: 9999;
}
#slides .slidesjs-pagination li {
  float: none;
}
@font-face {
    font-family: AvantGarde Demi;
    src: url(AvantGarde Demi.woff);
}
@font-face {
    font-family: AvantGarde;
    src: url(AvantGarde.woff);
}
@font-face {
    font-family: ITC Avant Garde Gothic;
    src: url(ITC Avant Garde Gothic.woff);
}
.topnav {
    background-color: #333;
    overflow: hidden;
    padding: 0 10px;
}
.topnav > img,
nav {
    display: inline-block;
    vertical-align: middle;
}
nav > ul {
    margin: 0;
}
.topnav .dropdown {
/*    display: block;
    float: left;
    text-align: center; */
}
.topnav a {
    color: white;
    display: block;
    font-size: 17px;
    text-decoration: none;
}
.topnav .dropdown > a {
    padding: 20px 16px;
}
.topnav .dropdown-content li > a {
    padding: 10px 16px;
}
.topnav ul > li > ul {
    background-color: #f76c38;
    display: none;
    padding: 0;
    position: absolute;
    width: 200px;
}
.topnav ul > li > ul > li {
    display: block;
    text-align: left;
}
body {
    border: 0;
    height: 100%;
    margin: 0;
    min-height: 100%;
    overflow-x: hidden;
}
.fa-6 {
    font-size: 1.5em;
}
.login {
    color: white;
    display: inline;
    font-family: AvantGarde;
    font-size: 11.433px;
    letter-spacing: .25em;
    padding-left: 15px;
}
.login a {
    color: white;
    text-decoration: none;
}
.login a:hover {
    color: #fe5b1f;
    text-decoration: none;
}
.container {
    width: 100% !important;
}
li.insurance {
/*    padding-top: 30px !important; */
}
li.our-story {
/*    padding-top: 30px !important; */
}
li.login-signup {
/*    padding-top: 30px !important; */
}
li.get-covered {
/*    margin-top: 15px;
    padding-bottom: 10px !important;
    padding-top: 10px !important; */
}
li.our-story {
    color: white;
    font-family: AvantGarde;
    letter-spacing: .30em;
}
li.login-signup {
    color: white;
    font-family: Adelle PE;
    font-size: 12px;
    font-style: italic;
    letter-spacing: .30em;
}
li.get-covered {
    border-color: #EF7440;
    border-style: solid;
    color: white;
    font-family: Adelle PE;
    letter-spacing: .30em;
}
li.get-covered:hover {
    background-color: #EF7440;
}
li.insurance {
    color: white;
    font-family: AvantGarde;
    letter-spacing: .30em;
    margin-left: 80px;
    margin-right: 80px;
}
nav > ul > li {
  display:inline-block;
}
.form-horizontal .form-control {
  border-radius:0;
  border:none;
  box-shadow:none;
  border-bottom:1px solid orange;
}
.form-horizontal .form-control:focus{
  box-shadow:none;
}
.container-fluid
{
  padding:0 !important;
}
.container
{
  padding:0 10px !important;
}
</code>```

Title: slideshow of forms by clicking dots on the right side of it

Body:
Now try this and u can see the demo here Demo

 <!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>SlidesJS Standard Code Example</title>
  <meta name="description" content="SlidesJS is a simple slideshow plugin for jQuery. Packed with a useful set of features to help novice and advanced developers alike create elegant and user-friendly slideshows.">
  <meta name="author" content="Nathan Searles">

  <!-- SlidesJS Required (if responsive): Sets the page width to the device width. -->
  <meta name="viewport" content="width=device-width">
  <!-- End SlidesJS Required -->

  <!-- CSS for slidesjs.com example -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
  <!-- End CSS for slidesjs.com example -->

  <!-- SlidesJS Optional: If you'd like to use this design -->
  <style>
    body {
      -webkit-font-smoothing: antialiased;
      font: normal 15px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif;
      color: #232525;
    }

    #slides,
    #slides2,
    #slides3 {
      display: none;
      margin-bottom:50px;
    }

    .slidesjs-navigation {
      margin-top:3px;
    }

    .slidesjs-previous {
      margin-right: 5px;
      float: left;
    }

    .slidesjs-next {
      margin-right: 5px;
      float: left;
    }

    .slidesjs-pagination {
      margin: 6px 0 0;
      float: right;
      list-style: none;
    }

    .slidesjs-pagination li {
      float: left;
      margin: 0 1px;
    }

    .slidesjs-pagination li a {
      display: block;
      width: 13px;
      height: 0;
      padding-top: 13px;
      background-image: url("https://s16.postimg.org/pt4k43i9x/pagination.png");
      background-position: 0 0;
      float: left;
      overflow: hidden;
    }

    .slidesjs-pagination li a.active,
    .slidesjs-pagination li a:hover.active {
      background-position: 0 -13px
    }

    .slidesjs-pagination li a:hover {
      background-position: 0 -26px
    }
    .navbar {
      overflow: hidden
    }
  </style>
  <!-- End SlidesJS Optional-->

  <!-- SlidesJS Required: These styles are required if you'd like a responsive slideshow -->
  <style>
    #slides {
      display: none
    }

    .container {
      margin: 0 auto
    }

    /* For tablets & smart phones */

    /* For smartphones */

  </style>
  <!-- SlidesJS Required: -->
</head>
<body>
<div class="topnav">
   <img src="https://s4.postimg.org/ojd13poal/northman_wordmark_CMYK.png">
   <nav>
      <ul>
         <li class="dropdown">
            <a href="#"><b>INSURANCE</b> <i class="fa fa-angle-down"></i></a>
            <ul class="dropdown-content">
               <li><a href="#"><i>INDIVIDUAL</i></a>
               </li>
               <li><a href="#"><i>CORPORATE</i></a>
               </li>
            </ul>
         </li>
         <li class="our-story">OUR STORY</li>
         <li class="login-signup">Log In | Sign up</li>
         <li class="get-covered">GET <strong style="font-style:italic">COVERED</strong>
         </li>
      </ul>
   </nav>
</div>
  <!-- SlidesJS Required: Start Slides -->
  <!-- The container is used to define the width of the slideshow -->
  <div class="container">
   <h3>INSURANCE FORM</h3>
   <h4><i>BASIC DETAILS</i></h4>
   <br>
    <div id="slides" class="container-fluid" >

  <form action="/action_page.php" class="form-horizontal">

      <div class="form-group">
         <div class="col-sm-6">
            <label>FIRST NAME</label>
            <input type="text" class="form-control" name="fname" value="Mickey 1">
         </div>
         <div class="col-sm-6">
            <label>LAST NAME</label>
            <input type="text" class="form-control" name="lname" value="Mouse">
         </div>
      </div>
      <div class="form-group">
         <div class="col-sm-6">
            <label>EMAIL</label>
            <input type="text" class="form-control" name="email" value="abc@host.com">
         </div>
         <div class="col-sm-6">
            <label>PHONE NUMBER</label>
            <input type="text" class="form-control" name="number" value="123-456-789">
         </div>
      </div>
      <div class="form-group">
         <div class="col-sm-6">
            <label>COUNTRY</label>
            <select name="country" class="form-control">
               <option value="canada">Canada</option>
            </select>
         </div>
         <div class="col-sm-3">
            <label>PROVINCE</label>
            <select name="province" class="form-control">
               <option value="ontario">ONTARIO</option>
            </select>
         </div>
         <div class="col-sm-3">
            <label>CITY</label>
            <select name="city" class="form-control">
               <option value="ottawa">OTTAWA</option>
            </select>
         </div>
      </div>
   </form>
  <form action="/action_page.php" class="form-horizontal">
      <div class="form-group">
         <div class="col-sm-6">
            <label>FIRST NAME</label>
            <input type="text" class="form-control" name="fname" value="Mickey 2">
         </div>
         <div class="col-sm-6">
            <label>LAST NAME</label>
            <input type="text" class="form-control" name="lname" value="Mouse">
         </div>
      </div>
      <div class="form-group">
         <div class="col-sm-6">
            <label>EMAIL</label>
            <input type="text" class="form-control" name="email" value="abc@host.com">
         </div>
         <div class="col-sm-6">
            <label>PHONE NUMBER</label>
            <input type="text" class="form-control" name="number" value="123-456-789">
         </div>
      </div>
      <div class="form-group">
         <div class="col-sm-6">
            <label>COUNTRY</label>
            <select name="country" class="form-control">
               <option value="canada">Canada</option>
            </select>
         </div>
         <div class="col-sm-3">
            <label>PROVINCE</label>
            <select name="province" class="form-control">
               <option value="ontario">ONTARIO</option>
            </select>
         </div>
         <div class="col-sm-3">
            <label>CITY</label>
            <select name="city" class="form-control">
               <option value="ottawa">OTTAWA</option>
            </select>
         </div>
      </div>

   </form>

      <a href="#" class="slidesjs-previous slidesjs-navigation"><i class="icon-chevron-left"></i></a>
      <a href="#" class="slidesjs-next slidesjs-navigation"><i class="icon-chevron-right"></i></a>
    </div>
  </div>
  <!-- End SlidesJS Required: Start Slides -->

  <!-- SlidesJS Required: Link to jQuery -->
  <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
  <!-- End SlidesJS Required -->

  <!-- SlidesJS Required: Link to jquery.slides.js -->
  <script src="js/jquery.slides.min.js"></script>
  <!-- End SlidesJS Required -->

  <!-- SlidesJS Required: Initialize SlidesJS with a jQuery doc ready -->
  <script>
    $(function() {
      $('#slides').slidesjs({
        width: 800,
        height: 528,
        navigation: false
      });
      $('.form-horizontal').css('padding','0 45px 0 0')

      /*
        To have multiple slideshows on the same page
        they just need to have separate IDs
      */
      $('#slides2').slidesjs({
        width: 800,
        height: 528,
        navigation: false,
        start: 3,
        play: {
          auto: true
        }
      });

      $('#slides3').slidesjs({
        width: 800,
        height: 528,
        navigation: false
      });
    });
  </script>
  <!-- End SlidesJS Required -->
</body>
</html>

and Style css

#slides {
  position: relative;
}
#slides .slidesjs-pagination {
  position: absolute;
  top: 11%; right: 0;
  transform: translateY(-50%);
  z-index: 9999;
}
#slides .slidesjs-pagination li {
  float: none;
}
@font-face {
    font-family: AvantGarde Demi;
    src: url(AvantGarde Demi.woff);
}
@font-face {
    font-family: AvantGarde;
    src: url(AvantGarde.woff);
}
@font-face {
    font-family: ITC Avant Garde Gothic;
    src: url(ITC Avant Garde Gothic.woff);
}
.topnav {
    background-color: #333;
    overflow: hidden;
    padding: 0 10px;
}
.topnav > img,
nav {
    display: inline-block;
    vertical-align: middle;
}
nav > ul {
    margin: 0;
}
.topnav .dropdown {
/*    display: block;
    float: left;
    text-align: center; */
}
.topnav a {
    color: white;
    display: block;
    font-size: 17px;
    text-decoration: none;
}
.topnav .dropdown > a {
    padding: 20px 16px;
}
.topnav .dropdown-content li > a {
    padding: 10px 16px;
}
.topnav ul > li > ul {
    background-color: #f76c38;
    display: none;
    padding: 0;
    position: absolute;
    width: 200px;
}
.topnav ul > li > ul > li {
    display: block;
    text-align: left;
}
body {
    border: 0;
    height: 100%;
    margin: 0;
    min-height: 100%;
    overflow-x: hidden;
}
.fa-6 {
    font-size: 1.5em;
}
.login {
    color: white;
    display: inline;
    font-family: AvantGarde;
    font-size: 11.433px;
    letter-spacing: .25em;
    padding-left: 15px;
}
.login a {
    color: white;
    text-decoration: none;
}
.login a:hover {
    color: #fe5b1f;
    text-decoration: none;
}
.container {
    width: 100% !important;
}
li.insurance {
/*    padding-top: 30px !important; */
}
li.our-story {
/*    padding-top: 30px !important; */
}
li.login-signup {
/*    padding-top: 30px !important; */
}
li.get-covered {
/*    margin-top: 15px;
    padding-bottom: 10px !important;
    padding-top: 10px !important; */
}
li.our-story {
    color: white;
    font-family: AvantGarde;
    letter-spacing: .30em;
}
li.login-signup {
    color: white;
    font-family: Adelle PE;
    font-size: 12px;
    font-style: italic;
    letter-spacing: .30em;
}
li.get-covered {
    border-color: #EF7440;
    border-style: solid;
    color: white;
    font-family: Adelle PE;
    letter-spacing: .30em;
}
li.get-covered:hover {
    background-color: #EF7440;
}
li.insurance {
    color: white;
    font-family: AvantGarde;
    letter-spacing: .30em;
    margin-left: 80px;
    margin-right: 80px;
}
nav > ul > li {
  display:inline-block;
}
.form-horizontal .form-control {
  border-radius:0;
  border:none;
  box-shadow:none;
  border-bottom:1px solid orange;
}
.form-horizontal .form-control:focus{
  box-shadow:none;
}
.container-fluid
{
  padding:0 !important;
}
.container
{
  padding:0 10px !important;
}


来源: stackexchange

问:
I want to add list of buttons in the same line in Swift 3.0
What I want is to add list of buttons (the number come from the service) to a uiview programmatically, so I think is I have to check if the space between the last button and the end of UIView is enough to add button or I have to go to the next line? Right?

Could you please help me on that?

Thanks,

答:
Here you go. Button added with auto layout constraints so it will work the same in all size classes :)</p>

```<code>var lastButton : UIButton? = nil

        for i in 0...5 {
            let button = UIButton()
            button.backgroundColor = UIColor.green
            button.setTitle("Button \(i)", for: .normal)
            button.sizeToFit()
            button.translatesAutoresizingMaskIntoConstraints = false

            if i == 0 {
                let viewComponents : [String : Any] = ["button" : button]
                self.view.addSubview(button)
                let horizontalConstraint = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(20)-[button]", options: [], metrics: nil, views: viewComponents)
                let verticalConstraint = NSLayoutConstraint.constraints(withVisualFormat: "V:|-(8)-[button]", options: [], metrics: nil, views: viewComponents)

                self.view.addConstraints(horizontalConstraint)
                self.view.addConstraints(verticalConstraint)
                self.view.layoutIfNeeded()
                lastButton = button
            }
            else {
                if (lastButton != nil) {
                    self.view.addSubview(button)
                    let viewComponents : [String : Any] = ["button" : button, "lastButton" : lastButton!]
                    if (lastButton!.frame.maxX + 8 + button.bounds.size.width) > self.view.bounds.size.width {
                        let horizontalConstraint = NSLayoutConstraint.constraints(withVisualFormat: "|-(8)-[button]", options: [], metrics: nil, views: viewComponents)
                        let verticalConstraint = NSLayoutConstraint.constraints(withVisualFormat: "V:[lastButton]-(8)-[button]", options: [], metrics: nil, views: viewComponents)

                        self.view.addConstraints(horizontalConstraint)
                        self.view.addConstraints(verticalConstraint)
                        self.view.layoutIfNeeded()
                        lastButton = button
                    }
                    else {
                        self.view.addSubview(button)
                        let horizontalConstraint = NSLayoutConstraint.constraints(withVisualFormat: "[lastButton]-(8)-[button]", options: [.alignAllTop], metrics: nil, views: viewComponents)

                        self.view.addConstraints(horizontalConstraint)
                        self.view.layoutIfNeeded()
                        lastButton = button
                    }
                }
            }
        }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here you go. Button added with auto layout constraints so it will work the same in all size classes :)

var lastButton : UIButton? = nil

        for i in 0...5 {
            let button = UIButton()
            button.backgroundColor = UIColor.green
            button.setTitle("Button \(i)", for: .normal)
            button.sizeToFit()
            button.translatesAutoresizingMaskIntoConstraints = false

            if i == 0 {
                let viewComponents : [String : Any] = ["button" : button]
                self.view.addSubview(button)
                let horizontalConstraint = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(20)-[button]", options: [], metrics: nil, views: viewComponents)
                let verticalConstraint = NSLayoutConstraint.constraints(withVisualFormat: "V:|-(8)-[button]", options: [], metrics: nil, views: viewComponents)

                self.view.addConstraints(horizontalConstraint)
                self.view.addConstraints(verticalConstraint)
                self.view.layoutIfNeeded()
                lastButton = button
            }
            else {
                if (lastButton != nil) {
                    self.view.addSubview(button)
                    let viewComponents : [String : Any] = ["button" : button, "lastButton" : lastButton!]
                    if (lastButton!.frame.maxX + 8 + button.bounds.size.width) > self.view.bounds.size.width {
                        let horizontalConstraint = NSLayoutConstraint.constraints(withVisualFormat: "|-(8)-[button]", options: [], metrics: nil, views: viewComponents)
                        let verticalConstraint = NSLayoutConstraint.constraints(withVisualFormat: "V:[lastButton]-(8)-[button]", options: [], metrics: nil, views: viewComponents)

                        self.view.addConstraints(horizontalConstraint)
                        self.view.addConstraints(verticalConstraint)
                        self.view.layoutIfNeeded()
                        lastButton = button
                    }
                    else {
                        self.view.addSubview(button)
                        let horizontalConstraint = NSLayoutConstraint.constraints(withVisualFormat: "[lastButton]-(8)-[button]", options: [.alignAllTop], metrics: nil, views: viewComponents)

                        self.view.addConstraints(horizontalConstraint)
                        self.view.layoutIfNeeded()
                        lastButton = button
                    }
                }
            }
        }


问:
Yii2 How to save same file name but different file or content?
How to save same name but different content for example, samplename.docx. Now i want to save it again but the result the same. When i create a new report and use the name samplename it will overwrite the other same name. So in the uploads folder the samplename.docx is only one. But in the dgView is more than one.

This is my controller:

```<code>public function actionCreate()
{
    $model = new reportDetails();
    if ($model->load(Yii::$app->request->post()))
    {
        $project =$model->doc_name;
        $model->upload_file= UploadedFile::getInstance($model,'doc_file');
        $model->upload_file->saveAs('uploads/'.$project.'.'.$model->upload_file->extension);
        $model->doc_file='uploads/'.$project.'.'.$model->upload_file->extension;
        $model->doc_name=$project.'.'.$model->upload_file->extension;
        $model->save();

        Yii::$app->getSession()->setFlash('success','Data saved!');
        return $this->redirect(['view','id'=> $model->report_id]);
    }

    else {
        return $this ->render('create', [
            'model'=>$model,
        ]);
    }
}
</code>```

This is my model:

```<code>public $upload_file;
public function rules()
{
    return [
        [['reference_no', 'subject', 'doc_for', 'doc_from', 'doc_date', 'doc_file', 'doc_name', 'drawer_id'], 'required'],
        [['doc_date'], 'safe'],
        [['drawer_id'], 'integer'],
        [['reference_no', 'doc_for', 'doc_from'], 'string', 'max' => 200],
        [['subject'], 'string', 'max' => 255],
        [['doc_file', 'doc_name'], 'string', 'max' => 50],
        [['user_id'],'string'],

    ];
}

/**
 * @inheritdoc
 */
public function attributeLabels()
{
    return [
        'report_id' => 'Report ID',
        'reference_no' => 'Reference No:',
        'subject' => 'Subject:',
        'doc_for' => 'For:',
        'doc_from' => 'From:',
        'doc_date' => 'Document Entry Date:',
        'doc_file' => 'Document File:',
        'doc_name' => 'Document Name:',
        'drawer_id' => 'Drawer ID:',
        'user_id' => 'Encoder Name:',
    ];
}
</code>```

And this is my form:

```<code> <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
        <?= Html::button('<i class="fa fa-plus"></i> Add Person', ['value' => Url::to('index.php?r=name/create'), 'class' => 'btn btn-custom-pos btn-success', 'id' => 'officialsfor']) ?>
        </br>
        </br>
  <?php Pjax::begin(['id' => 'for_from']) ?>
      <div class="col-sm-6">
     <?= $form->field($model, 'doc_for')->widget(Select2::classname(), [
           'data' => ArrayHelper::map(Name::find()->asArray()->all(),
            'name_id',
            function($model, $defaultValue){
              return $model['position'].' '.$model['fname'].' '.$model['mname'].' '.$model['lname'];
            }),
            'language' => 'en',
            'options' => ['placeholder' => 'Choose a person ...'],
            'pluginOptions' => [
                'allowClear' => true,
                'width' => 500,
             ],
            ]); ?>
      </div>
      <div class="col-sm-6">
    <?= $form->field($model, 'doc_from')->widget(Select2::classname(), [
           'data' => ArrayHelper::map(Name::find()->asArray()->all(),
           'name_id',
            function($model, $defaultValue){
            return $model['position'].' '.$model['fname'].' '.$model['mname'].' '.$model['lname'];
            }),
            'language' => 'en',
            'options' => ['placeholder' => 'Choose a person ...'],
            'pluginOptions' => [
                'allowClear' => true,
                'width' => 500,
            ],
            ]); ?>
 <?php Pjax::end(); ?>
      </div>
        </br>
        </br></br></br>
      <div class="broder" style=" border-radius: 5px; padding: 12px; ">
      </div>
  <div class="col-sm-6">
      <?= $form->field($model, 'user_id')->textInput(['type' => 'hidden','style'=>'width:500px;','placeholder' => 'Enter a Reference No....','value' =>ucfirst(Yii::$app->user->identity->first_name) . ' ' . ucfirst(Yii::$app->user->identity->middle_name) . ' ' . ucfirst(Yii::$app->user->identity->last_name)]) ?>
       <?= Html::activeLabel($model, 'user_id', ['label'=>ucfirst(Yii::$app->user->identity->first_name) . ' ' . ucfirst(Yii::$app->user->identity->middle_name) . ' ' . ucfirst(Yii::$app->user->identity->last_name),'style' => 'font-size: 21px;','class' => 'color']) ?>
      <br>
      <br>
      <?= $form->field($model, 'reference_no')->textInput(['style'=>'width:500px','placeholder' => 'Enter a Reference No....']) ?>
      <?= $form->field($model, 'subject')->textInput(['maxlength'=>true,'style'=>'width:500px','placeholder' => 'Enter a Subject....']) ?>
    <?= $form->field($model, 'doc_date')->widget(
        DatePicker::className(), [
            'inline' => false,
            'options' => ['placeholder' => 'Choose a Entry Date ...'],
            'clientOptions' => [
            'autoclose' => true,
            'format' => 'yyyy-mm-dd'
              ]
             ]);?>
  </div>
  <div class="col-sm-6" style="padding-top: 14px; ">
         </br>
         </br>
         </br></br>
    <?= $form->field($model, 'drawer_id')->textInput(['maxlength'=>true,'style'=>'width:500px','placeholder' => 'Enter a Drawer ID....', ]) ?>
    <?= $form->field($model, 'doc_name')->textInput(['maxlength'=>true,'style'=>'width:500px','placeholder' => 'Enter a Document Name....']) ?>
      <?= $form->field($model, 'doc_file')-> widget(
        FileInput::classname(),[
      'name' => 'doc_file',
      'options' => ['accept' => '.docx','.doc','.docs'],
      'pluginOptions' => [
          'showPreview' => false,
          'showCaption' => true,
          'showRemove' => true,
          'showUpload' => false
            ]
        ]);
      ?>
</code>```

答:
use</p>

```<code>if(file_exists('...')){
   // upload file with , new file name
}
else{
   // upload file
}
</code>```

Body:
How to save same name but different content for example, samplename.docx. Now i want to save it again but the result the same. When i create a new report and use the name samplename it will overwrite the other same name. So in the uploads folder the samplename.docx is only one. But in the dgView is more than one.

This is my controller:

public function actionCreate()
{
    $model = new reportDetails();
    if ($model->load(Yii::$app->request->post()))
    {
        $project =$model->doc_name;
        $model->upload_file= UploadedFile::getInstance($model,'doc_file');
        $model->upload_file->saveAs('uploads/'.$project.'.'.$model->upload_file->extension);
        $model->doc_file='uploads/'.$project.'.'.$model->upload_file->extension;
        $model->doc_name=$project.'.'.$model->upload_file->extension;
        $model->save();

        Yii::$app->getSession()->setFlash('success','Data saved!');
        return $this->redirect(['view','id'=> $model->report_id]);
    }

    else {
        return $this ->render('create', [
            'model'=>$model,
        ]);
    }
}

This is my model:

public $upload_file;
public function rules()
{
    return [
        [['reference_no', 'subject', 'doc_for', 'doc_from', 'doc_date', 'doc_file', 'doc_name', 'drawer_id'], 'required'],
        [['doc_date'], 'safe'],
        [['drawer_id'], 'integer'],
        [['reference_no', 'doc_for', 'doc_from'], 'string', 'max' => 200],
        [['subject'], 'string', 'max' => 255],
        [['doc_file', 'doc_name'], 'string', 'max' => 50],
        [['user_id'],'string'],

    ];
}

/**
 * @inheritdoc
 */
public function attributeLabels()
{
    return [
        'report_id' => 'Report ID',
        'reference_no' => 'Reference No:',
        'subject' => 'Subject:',
        'doc_for' => 'For:',
        'doc_from' => 'From:',
        'doc_date' => 'Document Entry Date:',
        'doc_file' => 'Document File:',
        'doc_name' => 'Document Name:',
        'drawer_id' => 'Drawer ID:',
        'user_id' => 'Encoder Name:',
    ];
}

And this is my form:

 <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
        <?= Html::button(' Add Person', ['value' => Url::to('index.php?r=name/create'), 'class' => 'btn btn-custom-pos btn-success', 'id' => 'officialsfor']) ?>

  <?php Pjax::begin(['id' => 'for_from']) ?>

     <?= $form->field($model, 'doc_for')->widget(Select2::classname(), [
           'data' => ArrayHelper::map(Name::find()->asArray()->all(),
            'name_id',
            function($model, $defaultValue){
              return $model['position'].' '.$model['fname'].' '.$model['mname'].' '.$model['lname'];
            }),
            'language' => 'en',
            'options' => ['placeholder' => 'Choose a person ...'],
            'pluginOptions' => [
                'allowClear' => true,
                'width' => 500,
             ],
            ]); ?>

    <?= $form->field($model, 'doc_from')->widget(Select2::classname(), [
           'data' => ArrayHelper::map(Name::find()->asArray()->all(),
           'name_id',
            function($model, $defaultValue){
            return $model['position'].' '.$model['fname'].' '.$model['mname'].' '.$model['lname'];
            }),
            'language' => 'en',
            'options' => ['placeholder' => 'Choose a person ...'],
            'pluginOptions' => [
                'allowClear' => true,
                'width' => 500,
            ],
            ]); ?>
 <?php Pjax::end(); ?>

      <?= $form->field($model, 'user_id')->textInput(['type' => 'hidden','style'=>'width:500px;','placeholder' => 'Enter a Reference No....','value' =>ucfirst(Yii::$app->user->identity->first_name) . ' ' . ucfirst(Yii::$app->user->identity->middle_name) . ' ' . ucfirst(Yii::$app->user->identity->last_name)]) ?>
       <?= Html::activeLabel($model, 'user_id', ['label'=>ucfirst(Yii::$app->user->identity->first_name) . ' ' . ucfirst(Yii::$app->user->identity->middle_name) . ' ' . ucfirst(Yii::$app->user->identity->last_name),'style' => 'font-size: 21px;','class' => 'color']) ?>

      <?= $form->field($model, 'reference_no')->textInput(['style'=>'width:500px','placeholder' => 'Enter a Reference No....']) ?>
      <?= $form->field($model, 'subject')->textInput(['maxlength'=>true,'style'=>'width:500px','placeholder' => 'Enter a Subject....']) ?>
    <?= $form->field($model, 'doc_date')->widget(
        DatePicker::className(), [
            'inline' => false,
            'options' => ['placeholder' => 'Choose a Entry Date ...'],
            'clientOptions' => [
            'autoclose' => true,
            'format' => 'yyyy-mm-dd'
              ]
             ]);?>

    <?= $form->field($model, 'drawer_id')->textInput(['maxlength'=>true,'style'=>'width:500px','placeholder' => 'Enter a Drawer ID....', ]) ?>
    <?= $form->field($model, 'doc_name')->textInput(['maxlength'=>true,'style'=>'width:500px','placeholder' => 'Enter a Document Name....']) ?>
      <?= $form->field($model, 'doc_file')-> widget(
        FileInput::classname(),[
      'name' => 'doc_file',
      'options' => ['accept' => '.docx','.doc','.docs'],
      'pluginOptions' => [
          'showPreview' => false,
          'showCaption' => true,
          'showRemove' => true,
          'showUpload' => false
            ]
        ]);
      ?>

Body:
use

if(file_exists('...')){
   // upload file with , new file name
}
else{
   // upload file
}


问:
How to return object with its ManyToManyField related object
I have a model, for example, A has a field xxx (ManyToManyField with B model). How can I query and return like:

```<code>{
   'f1': 'xxx',
   'f2': 'yyy',
    photos: [{photo1}, {photo2},...]
}
</code>```

Any help is appreciated. I'm django newbie :D

答:
Assuming these models:

from django.db import models

class LoremIpsum(models.Model):
    identifier = models.CharField()
    photos = models.ManyToManyField('Photo')

class Photo(models.Model):
    filename = models.CharField()
```

<p>Because the <code>LoremIpsum.photos</code> field is a <code>ManyToManyField</code>, its value will act as a <code>QuerySet</code>:</p>

<pre class="lang-python prettyprint-override"><code>lorem_ipsum = LoremIpsum.objects.get(identifier="dolor")
photo_filenames = [photo.filename for photo in lorem_ipsum.photos.all()]
</code>```

Body:
I have a model, for example, A has a field xxx (ManyToManyField with B model). How can I query and return like:

{
   'f1': 'xxx',
   'f2': 'yyy',
    photos: [{photo1}, {photo2},...]
}

Any help is appreciated. I'm django newbie :D

Body:
Assuming these models:

from django.db import models

class LoremIpsum(models.Model):
    identifier = models.CharField()
    photos = models.ManyToManyField('Photo')

class Photo(models.Model):
    filename = models.CharField()

Because the LoremIpsum.photos field is a ManyToManyField, its value will act as a QuerySet:

lorem_ipsum = LoremIpsum.objects.get(identifier="dolor")
photo_filenames = [photo.filename for photo in lorem_ipsum.photos.all()]


问:
Django table2: Add row with the edittext field
I have designed the the table with the table2.is the screen shot of my table as shown below:

This row of each column are read only i.e. screenshot.I want the row of each column should be editable.Can we have the "edittext" as column of each row in the table2 in django?

Below is my model.py

```<code>from django.db import models

    class Person(models.Model):
        date = models.CharField(verbose_name="Date",max_length=255)
        project = models.CharField(verbose_name="Project",max_length=255)
        release = models.CharField(verbose_name="Release",max_length=255)
        feature = models.CharField(verbose_name="Feature",max_length=255)
        module_name = models.CharField(verbose_name="Module Name",max_length=255)
        hours_spent = models.CharField(verbose_name="Hours spent",max_length=255)
        comment = models.CharField(verbose_name="Comment",max_length=255)
</code>```

Below is the table.py.

```<code>import django_tables2 as tables
from .models import Person

class PersonTable(tables.Table):
    class Meta:
        model = Person
        # add class="paleblue" to <table> tag
        attrs = {'class': 'paleblue'}
        #fields = ('name') # fields to display
</code>```

How should I edit my model.py,table.py? Please help.

答:
To make cells editable you can use html5 contenteditable attribute.

So you need to have this attribute in each td of your table.
You can specify td attributes in Column definition:

```<code>class ProductsTable(tables.Table):
    date = tables.columns.Column(verbose_name="Date",max_length=255,attrs={'td': {'contenteditable': ''}})
</code>```

or you can probably override __init__ method of the table to add this attribute to every column so you don't have to specify it multiple times.

This makes your table editable but it doesn't mean that you can modify your database through this table yet. You will have to do some magic with AJAX and event handling.

Check this link

Body:
I have designed the the table with the table2.is the screen shot of my table as shown below:

This row of each column are read only i.e. screenshot.I want the row of each column should be editable.Can we have the "edittext" as column of each row in the table2 in django?

Below is my model.py

from django.db import models

    class Person(models.Model):
        date = models.CharField(verbose_name="Date",max_length=255)
        project = models.CharField(verbose_name="Project",max_length=255)
        release = models.CharField(verbose_name="Release",max_length=255)
        feature = models.CharField(verbose_name="Feature",max_length=255)
        module_name = models.CharField(verbose_name="Module Name",max_length=255)
        hours_spent = models.CharField(verbose_name="Hours spent",max_length=255)
        comment = models.CharField(verbose_name="Comment",max_length=255)

Below is the table.py.

import django_tables2 as tables
from .models import Person

class PersonTable(tables.Table):
    class Meta:
        model = Person
        # add class="paleblue" to
 tag
        attrs = {'class': 'paleblue'}
        #fields = ('name') # fields to display

How should I edit my model.py,table.py? Please help.

Body:
To make cells editable you can use html5 contenteditable attribute.

So you need to have this attribute in each td of your table.
You can specify td attributes in Column definition:

class ProductsTable(tables.Table):
    date = tables.columns.Column(verbose_name="Date",max_length=255,attrs={'td': {'contenteditable': ''}})

or you can probably override __init__ method of the table to add this attribute to every column so you don't have to specify it multiple times.

This makes your table editable but it doesn't mean that you can modify your database through this table yet. You will have to do some magic with AJAX and event handling.

Check this link


问:
In R, how do I use apply() with data frames?
apply() allows you to select whether rows or columns with MARGIN=1 or MARGIN=2, respectively.

But apply only works on matrices.

For example, I have three rows of header information and 3 columns of descriptive information.  I need to combine these into row names and row names and column names, respectively.  So I can't easily use read.table() and skip the first 3 rows, and then delete the first 3 columns to get my matrix right away.

This doesn't work on data frames, just matrices

```<code>rownames(df)<-apply(df[,1:3], MARGIN=1,FUN=function(x){paste(x,sep=".")})
</code>```

答:
You can exclude the non-numeric columns/rows and deploy apply function onto the numeric rows.

Consider an example:
If a data frame has 4 columns out of which the first one belongs to the character class, then use below code:

```<code>apply(Data.df[,2:4],2,func_name)
</code>```

Body:
apply() allows you to select whether rows or columns with MARGIN=1 or MARGIN=2, respectively.

But apply only works on matrices.

For example, I have three rows of header information and 3 columns of descriptive information.  I need to combine these into row names and row names and column names, respectively.  So I can't easily use read.table() and skip the first 3 rows, and then delete the first 3 columns to get my matrix right away.

This doesn't work on data frames, just matrices

rownames(df)<-apply(df[,1:3], MARGIN=1,FUN=function(x){paste(x,sep=".")})

Body:
You can exclude the non-numeric columns/rows and deploy apply function onto the numeric rows.

Consider an example:
If a data frame has 4 columns out of which the first one belongs to the character class, then use below code:

apply(Data.df[,2:4],2,func_name)


问:
Boostrap modal element offset giving zero
To scroll to an element in my Bootstrap modal, I can check the offset of the element. There are for instance 8 div's, each with their own id (#row-1, #row-2, etc.). If I open the modal and then input the following into the console, I get the correct offset value.

```<code>$('#row-6').offset()['top'];
</code>```

But when I console.log this into the code itself, after opening the modal with .modal('show'), I get 0 back.

How can this difference occur? I tried all the solutions I could find on here, but all solutions gave me the same 0.

My problem would also be solved if I could scroll to the element in any other way with JavaScript.

答:
You must wait for the modal to be shown:</p>

```<code>  // The modal is shown
    $('#yourModal').on('shown.bs.modal', function() {
      // Get the right offset
      var offset = $("#yourelement").offset();
      var offsetTop = offset.top;
      var offsetLeft = offset.left;
    });
</code>```

Body:
To scroll to an element in my Bootstrap modal, I can check the offset of the element. There are for instance 8 div's, each with their own id (#row-1, #row-2, etc.). If I open the modal and then input the following into the console, I get the correct offset value.

$('#row-6').offset()['top'];

But when I console.log this into the code itself, after opening the modal with .modal('show'), I get 0 back.

How can this difference occur? I tried all the solutions I could find on here, but all solutions gave me the same 0.

My problem would also be solved if I could scroll to the element in any other way with JavaScript.

Body:
You must wait for the modal to be shown:

  // The modal is shown
    $('#yourModal').on('shown.bs.modal', function() {
      // Get the right offset
      var offset = $("#yourelement").offset();
      var offsetTop = offset.top;
      var offsetLeft = offset.left;
    });


问:
The final field cannot be assigned, for an interface
I have a class Product and an interface LargeProduct. Product implements LargeProduct.

LargeProduct has a variable height which has getter and setter methods which have to be implemented in the Product class.

The height variable in LargeProduct is defined like so:

```<code>public int height = null;
</code>```

The getter method works fine:

```<code>public int getHeight() {
    return height;
}
</code>```

But the setter method does not:

```<code>public void setHeight(int height) {
    this.height = height;
}
</code>```

Errors:

```<code>The final field LargeProduct.height cannot be assigned
The static field LargeProduct.height should be accessed in a static way
</code>```

I'm not sure which error it's actually giving.. I'm using Eclipse and when I hover it gives the first error, and at the bottom of the window it gives the second error.

答:
You can't assign a value to a final field. Declare height in Product as</p>

```<code>private int height;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a class Product and an interface LargeProduct. Product implements LargeProduct.

LargeProduct has a variable height which has getter and setter methods which have to be implemented in the Product class.

The height variable in LargeProduct is defined like so:

public int height = null;

The getter method works fine:

public int getHeight() {
    return height;
}

But the setter method does not:

public void setHeight(int height) {
    this.height = height;
}

Errors:

The final field LargeProduct.height cannot be assigned
The static field LargeProduct.height should be accessed in a static way

I'm not sure which error it's actually giving.. I'm using Eclipse and when I hover it gives the first error, and at the bottom of the window it gives the second error.

Body:
You can't assign a value to a final field. Declare height in Product as

private int height;


问:
Why phpMyAdmin is not importing my table?
I'm a designer, but as there's no programmer in my company I have to start studing programming. Which I did only somedays ago (and I have only  a html and css knowledge background) so pleasepleaseplease don't take any knowledge for granted if you can answer me!

I'm studing PHP and MySQL using "PHP & MySQL in easy steps" by Mike McGranth (if any of you have it I'm at page 90/91). So, the task is simple: write a .sql file and create a table in phpMyAdmin with it.

Since it's an exercise from a book I just have to write as it's written on the page and test it; yes, I have the solution-file too, but the point is I can't see the difference between my code, which can't be processed by phpMyAdmin, and the solution-code, which gives no problem.

The .sql file written by me is this:

```<code>CREATE TABLE IF NOT EXISTS products
(
id INT UNIQUE AUTO_INCREMENT ,
code INT NOT_NULL ,
name VARCHAR(25) NOT NULL ,
quantity INT DEFAULT 1 NULL ,
price DECIMAL(6,2) NOT NULL
) ;
</code>```

And the solution-file code is this:

```<code>CREATE TABLE IF NOT EXISTS products
(
  id        INT UNIQUE  AUTO_INCREMENT ,
  code      INT     NOT NULL ,
  name      VARCHAR(25)     NOT NULL ,
  quantity  INT     DEFAULT 1 NULL ,
  price     DECIMAL(6,2)    NOT NULL
) ;
</code>```

This is also how the look like in a code-editor program:

This is the error that phpMyAdmin gives to me (if the japanese part is important I can add the translation):

Since I have a solution, why do I ask? Because maybe I've done just a small mistake, but if I don't understand it I'm afraid to do it again when handling bigger files, maybe a client db, real work, not just an exercise.
So, if anyone will be so kind to explain it to me he/she will have my ethernal gratitude!

答:
You need to remove underscore from NOT_NULL in the code column. So replace

```<code>code INT NOT_NULL ,
</code>```

To

```<code>code INT NOT NULL ,
</code>```

Body:
I'm a designer, but as there's no programmer in my company I have to start studing programming. Which I did only somedays ago (and I have only  a html and css knowledge background) so pleasepleaseplease don't take any knowledge for granted if you can answer me!

I'm studing PHP and MySQL using "PHP & MySQL in easy steps" by Mike McGranth (if any of you have it I'm at page 90/91). So, the task is simple: write a .sql file and create a table in phpMyAdmin with it.

Since it's an exercise from a book I just have to write as it's written on the page and test it; yes, I have the solution-file too, but the point is I can't see the difference between my code, which can't be processed by phpMyAdmin, and the solution-code, which gives no problem.

The .sql file written by me is this:

CREATE TABLE IF NOT EXISTS products
(
id INT UNIQUE AUTO_INCREMENT ,
code INT NOT_NULL ,
name VARCHAR(25) NOT NULL ,
quantity INT DEFAULT 1 NULL ,
price DECIMAL(6,2) NOT NULL
) ;

And the solution-file code is this:

CREATE TABLE IF NOT EXISTS products
(
  id        INT UNIQUE  AUTO_INCREMENT ,
  code      INT     NOT NULL ,
  name      VARCHAR(25)     NOT NULL ,
  quantity  INT     DEFAULT 1 NULL ,
  price     DECIMAL(6,2)    NOT NULL
) ;

This is also how the look like in a code-editor program:

This is the error that phpMyAdmin gives to me (if the japanese part is important I can add the translation):

Since I have a solution, why do I ask? Because maybe I've done just a small mistake, but if I don't understand it I'm afraid to do it again when handling bigger files, maybe a client db, real work, not just an exercise.
So, if anyone will be so kind to explain it to me he/she will have my ethernal gratitude!

Body:
You need to remove underscore from NOT_NULL in the code column. So replace

code INT NOT_NULL ,

To

code INT NOT NULL ,


问:
Uploading/Saving videos not working in PHP
If a user inputs "0" in the "media_type" text box, it runs the image upload code and if you put "1" it runs the video upload code. The problem is with the video section because when i upload a video, it doesn't display anything. But when i input an image, and go to the image section, it works. Here is my code

PHP

```<code><?php

if(isset($_POST['submit'])){

    $media_type = addslashes($_POST['media_type']);

    if($media_type !=0 && $media_type !=1){

        die (json_encode([
        "Status" => " Failed",
        "Message" => " Error 404"
    ]));
        exit;
    }

    if(@getimagesize($_FILES["file"]["tmp_name"])==false){

        echo json_encode([

            "Status" => " Failed",
            "Message" => " No file selected..."
        ]);
        exit;
    }

    if(@getimagesize($_FILES['file']['tmp_name']) ==FALSE || $_POST['user_id'] == "" || $_POST['media_type'] =="" || $_POST['category1'] ==""){

        echo json_encode([
            "Status" => "Failed",
            "Message" => "There were values missing"

        ]);

    die("");
    }

function imageUpload(){
    $userid = addslashes($_POST['user_id']);
    $category1 = addslashes($_POST['category1']);
    $category2 = addslashes($_POST['category2']);
    $category3 = addslashes($_POST['category3']);

//if file is there

    $target = "images/";

    $target_file = addslashes($target . basename($_FILES["file"]["name"]));

    if(file_exists($target_file)){

        echo json_encode([
            "Status" => " Failed",
            "Message" => " Sorry, file already exists..."
        ]);
        exit;
    }
if(move_uploaded_file($_FILES["file"]["tmp_name"], $target_file))
{

    $db = mysqli_connect("localhost", "root", "");
    mysqli_select_db($db, "magicsever");

    if(mysqli_connect_error()){

        die ("Database connection error");
    }

$image = addslashes($_FILES['file']['tmp_name']);
$name = addslashes($_FILES['file']['name']);

$sql = "INSERT INTO classified_images (`user_id`,`image`, `img_path`, `img_category_1`,`img_category_2`, `img_category_3`)VALUES('$userid','$image','$name','$category1','$category2','$category3')";
$final = mysqli_query($db, $sql);

echo json_encode([
"Message" => "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.",
"Status" => "OK",
"userId" => $_POST["user_id"]
]);
}else{

echo json_encode([
"Message" => "Sorry, there was an error uploading your file.",
"Status" => "Error",
"userId" => $_POST["user_id"]
]);

}
}

function videoUpload(){
    $userid = addslashes($_POST['user_id']);
    $category1 = addslashes($_POST['category1']);
    $category2 = addslashes($_POST['category2']);
    $category3 = addslashes($_POST['category3']);
    // Check if file was submited

    $target = "videos/";

    $target_file = addslashes($target . basename($_FILES["file"]["name"]));

    // Check if file already exists
    if(file_exists($target_file)){

        echo json_encode([
            "Status" => " Failed",
            "Message" => " Sorry, file already exists..."
        ]);
        exit;
    }

    // Check file size not > 500Mb
    if($_FILES["file"]["size"] > 500000000){

        echo json_encode([

            "Status" => " Failed",
            "Message" => " Sorry, file is too large."
        ]);
        exit;
    }

        if(move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)){

            $db = mysqli_connect("localhost", "root", "");
    mysqli_select_db($db, "magicsever");

    if(mysqli_connect_error()){

        die ("Database connection error");
    }

    $video = addslashes($_FILES['file']['tmp_name']);
        $name = addslashes($_FILES['file']['name']);

    $sql = "INSERT INTO classified_videos (`user_id`, `vid_path`, `vid_category_1`, `vid_category_2`, `vid_category_3`, `video`)VALUES('$userid','$name','$category1','$category2','$category3','$video')";
    $final = mysqli_query($db, $sql);

            echo json_encode([

                "Status" => " Success",
                "Message" => " The file ". basename($_FILES["file"]["name"]). " has been uploaded.",
                "userId" => $_POST["user_id"]
            ]);
        }else{

            echo json_encode([

                "Status" => " Failed",
                "Message" => " Sorry, there was an error uploaded your file"
            ]);
            exit;
        }

    //Connect to database

}
    if($media_type ==0){

        imageUpload();
    }else if($media_type ==1){

        videoUpload();
    }
}
?>
</code>```

HTML

```<code>    <form method="post" enctype="multipart/form-data">

<input type="file" name="file">

<br></br>
<input type="text" name="user_id" placeholder="User id...">
<br></br>
<input type="text" name="media_type" placeholder="(0)Image...(1)Video">
<br></br>
<input type="text" name="category1" placeholder="MediaTag#1...">
<br></br>
<input type="text" name="category2" placeholder="MediaTag#2...">
<br></br>
<input type="text" name="category3" placeholder="MediaTag#3...">
    <br></br>
<input type="submit" name="submit" value="upload">

</form>
</code>```

答:
In case of video, your control for image size is always giving false (or nonsensical values):

```<code>if(@getimagesize($_FILES["file"]["tmp_name"])==false){
</code>```

That is why you are receiving the "No file selected" message.
Check if you are getting video or images and run that control just in the right case.

As you can read in the documentation getimagesize() :

Caution
  This function expects filename to be a valid image file. If a non-image file is supplied, it may be incorrectly detected as an image and the function will return successfully, but the array may contain nonsensical values.

Body:
If a user inputs "0" in the "media_type" text box, it runs the image upload code and if you put "1" it runs the video upload code. The problem is with the video section because when i upload a video, it doesn't display anything. But when i input an image, and go to the image section, it works. Here is my code

PHP

<?php

if(isset($_POST['submit'])){

    $media_type = addslashes($_POST['media_type']);

    if($media_type !=0 && $media_type !=1){

        die (json_encode([
        "Status" => " Failed",
        "Message" => " Error 404"
    ]));
        exit;
    }

    if(@getimagesize($_FILES["file"]["tmp_name"])==false){

        echo json_encode([

            "Status" => " Failed",
            "Message" => " No file selected..."
        ]);
        exit;
    }

    if(@getimagesize($_FILES['file']['tmp_name']) ==FALSE || $_POST['user_id'] == "" || $_POST['media_type'] =="" || $_POST['category1'] ==""){

        echo json_encode([
            "Status" => "Failed",
            "Message" => "There were values missing"

        ]);

    die("");
    }

function imageUpload(){
    $userid = addslashes($_POST['user_id']);
    $category1 = addslashes($_POST['category1']);
    $category2 = addslashes($_POST['category2']);
    $category3 = addslashes($_POST['category3']);

//if file is there

    $target = "images/";

    $target_file = addslashes($target . basename($_FILES["file"]["name"]));

    if(file_exists($target_file)){

        echo json_encode([
            "Status" => " Failed",
            "Message" => " Sorry, file already exists..."
        ]);
        exit;
    }
if(move_uploaded_file($_FILES["file"]["tmp_name"], $target_file))
{

    $db = mysqli_connect("localhost", "root", "");
    mysqli_select_db($db, "magicsever");

    if(mysqli_connect_error()){

        die ("Database connection error");
    }

$image = addslashes($_FILES['file']['tmp_name']);
$name = addslashes($_FILES['file']['name']);

$sql = "INSERT INTO classified_images (`user_id`,`image`, `img_path`, `img_category_1`,`img_category_2`, `img_category_3`)VALUES('$userid','$image','$name','$category1','$category2','$category3')";
$final = mysqli_query($db, $sql);

echo json_encode([
"Message" => "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.",
"Status" => "OK",
"userId" => $_POST["user_id"]
]);
}else{

echo json_encode([
"Message" => "Sorry, there was an error uploading your file.",
"Status" => "Error",
"userId" => $_POST["user_id"]
]);

}
}

function videoUpload(){
    $userid = addslashes($_POST['user_id']);
    $category1 = addslashes($_POST['category1']);
    $category2 = addslashes($_POST['category2']);
    $category3 = addslashes($_POST['category3']);
    // Check if file was submited

    $target = "videos/";

    $target_file = addslashes($target . basename($_FILES["file"]["name"]));

    // Check if file already exists
    if(file_exists($target_file)){

        echo json_encode([
            "Status" => " Failed",
            "Message" => " Sorry, file already exists..."
        ]);
        exit;
    }

    // Check file size not > 500Mb
    if($_FILES["file"]["size"] > 500000000){

        echo json_encode([

            "Status" => " Failed",
            "Message" => " Sorry, file is too large."
        ]);
        exit;
    }

        if(move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)){

            $db = mysqli_connect("localhost", "root", "");
    mysqli_select_db($db, "magicsever");

    if(mysqli_connect_error()){

        die ("Database connection error");
    }

    $video = addslashes($_FILES['file']['tmp_name']);
        $name = addslashes($_FILES['file']['name']);

    $sql = "INSERT INTO classified_videos (`user_id`, `vid_path`, `vid_category_1`, `vid_category_2`, `vid_category_3`, `video`)VALUES('$userid','$name','$category1','$category2','$category3','$video')";
    $final = mysqli_query($db, $sql);

            echo json_encode([

                "Status" => " Success",
                "Message" => " The file ". basename($_FILES["file"]["name"]). " has been uploaded.",
                "userId" => $_POST["user_id"]
            ]);
        }else{

            echo json_encode([

                "Status" => " Failed",
                "Message" => " Sorry, there was an error uploaded your file"
            ]);
            exit;
        }

    //Connect to database

}
    if($media_type ==0){

        imageUpload();
    }else if($media_type ==1){

        videoUpload();
    }
}
?>

HTML

    <form method="post" enctype="multipart/form-data">

<input type="file" name="file">

<input type="text" name="user_id" placeholder="User id...">

<input type="text" name="media_type" placeholder="(0)Image...(1)Video">

<input type="text" name="category1" placeholder="MediaTag#1...">

<input type="text" name="category2" placeholder="MediaTag#2...">

<input type="text" name="category3" placeholder="MediaTag#3...">

<input type="submit" name="submit" value="upload">

</form>

Body:
In case of video, your control for image size is always giving false (or nonsensical values):

if(@getimagesize($_FILES["file"]["tmp_name"])==false){

That is why you are receiving the "No file selected" message.
Check if you are getting video or images and run that control just in the right case.

As you can read in the documentation getimagesize() :

Caution
  This function expects filename to be a valid image file. If a non-image file is supplied, it may be incorrectly detected as an image and the function will return successfully, but the array may contain nonsensical values.


问:
Swift return result of function calls
I'm completing some exercism exercises. One is a Binary tree (although the context is not relevant to the question as I have experienced this previously in Swift)

I would like to put the following function on one line as:

```<code>func allData () -> [Int] {
    return ( left?.allData() ?? [] ) + [data] + ( right?.allData() ?? [] )
}
</code>```

But the error is 'Int' is not convertible to '[Int]'

Ok, but splitting into separate lines is fine:

```<code>func allData () -> [Int] {
    let leftdata = left?.allData() ?? []
    let rightdata = right?.allData() ?? []
    return ( leftdata ) + [data] + ( rightdata )
}
</code>```

In fact it will compile with either the left data, right data and [data], but not both.

Within exercism I can see that people did not solve this in one line.

So why is

```<code>return ( left?.allData() ?? [] ) + [data] + ( right?.allData() ?? [] )
</code>```

invalid?

答: In many cases, xcode does not compile a statement because it is too complex to be compiled n a reasonable time. Therefore, splitting the statement solves the issue.</p>

Title: Swift return result of function calls

Body:
I'm completing some exercism exercises. One is a Binary tree (although the context is not relevant to the question as I have experienced this previously in Swift)

I would like to put the following function on one line as:

func allData () -> [Int] {
    return ( left?.allData() ?? [] ) + [data] + ( right?.allData() ?? [] )
}

But the error is 'Int' is not convertible to '[Int]'

Ok, but splitting into separate lines is fine:

func allData () -> [Int] {
    let leftdata = left?.allData() ?? []
    let rightdata = right?.allData() ?? []
    return ( leftdata ) + [data] + ( rightdata )
}

In fact it will compile with either the left data, right data and [data], but not both.

Within exercism I can see that people did not solve this in one line.

So why is

return ( left?.allData() ?? [] ) + [data] + ( right?.allData() ?? [] )

invalid?


问:
What needed to be change for Paypal when updating http to https?
I'm in the mid of updating my server from http to https, even do a simple test on paypal redirect and it seems to work redirecting it back to https. However I want to make sure i got it right, is there any settings i needed to update in paypal?</p>

答:
If you are using PayPal Standard with PDT / Auto-Return setup in PayPal then you may need to change the values there for your Return URL.  Also, if you have IPN configured in PayPal you may want to update that.  Otherwise you should be good to go.

Side note, it would be good to go ahead and setup rules on your server, too, so that any traffic that comes to http:// gets 301 redirected to https://.  This can be done easily with an htaccess file if you're running on Apache.


问:
Output status messages to the console from cypher neo4j-shell
I'm running some Neo4j cypher queries using neo4j-shell. They have long execution times as I am importing large CSV files.

I would like to output some messages to the console as each stage of the import completes, so that we can see the import progress at run-time without having to wait for the execution to complete.

I've checked the Cypher RefCard and can't find an example of this. Does cypher support outputting to the shell console window?

答:
I have done this using RETURN. But each RETURN value is printed twice!
Not sure what exactly is happening there. But for debugging that is fine.

```<code>RETURN "Removing existing data...";
MATCH (n)
DETACH DELETE n;
RETURN "Existing data removed";
</code>```

Body:
I have done this using RETURN. But each RETURN value is printed twice!
Not sure what exactly is happening there. But for debugging that is fine.

RETURN "Removing existing data...";
MATCH (n)
DETACH DELETE n;
RETURN "Existing data removed";


问:
Object Moved Here - RedirectToAction
Again, after tiresome attempts to solve this annoying issue, I am back here. I am experiencing an "Object moved here" on my view in my MVC5 application after some return RedirectToAction("Index", "Roles", model); action on my controller.

I have considered solutions from the following links:

RedirectToAction and "Object moved to here" error

ASP.NET MVC Website: Object Moved to Here

https://forums.asp.net/t/1643235.aspx?+Object+moved+to+here+problem
but none are applicable to my problem.

Before anyone marks this as a duplicate, please consider the scenario below:

But now the weird thing is that after I have clicked on the 'here' link and it now renders my view - it has a horizontal split screen showing the correct display of my view on top and below the view that throws an Http Error Code - in this case its Error Code 500 : Internal Server Error.

The reason why I am getting the http status code error is due to this unanswered question here (one of many) :

Failed to load resource: Uncaught TypeError: $(...).select2 is not a function

But that is besides the point right now.

Controller:

```<code>        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create([Bind(Include = "Name,Description")] ApplicationRole model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var role = new ApplicationRole()
                    {
                        Name = model.Name,
                        Description = model.Description
                    };

                    var roleManager = new RoleManager<ApplicationRole>(new RoleStore<ApplicationRole>(db));
                    var result = await roleManager.CreateAsync(role);
                    if (result.Succeeded)
                    {
                        return RedirectToAction("Index", "Roles", model);
                    }
                    else
                    {
                        AddErrors(result);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //Below is my index method in my Roles controller which is the action that redirection needs to route to:

        [Route("/Roles")]
        public ActionResult Index()
        {
            if (TempData["StatusMessage"] != null)
            {
                ViewBag.StatusMessage = TempData["StatusMessage"].ToString();
            }
            else
            {
                ViewBag.StatusMessage = "";
            }

            var roles = db.Roles.ToList();
            return View("Index", roles);
        }

        //GET method to create view
        public ActionResult Create()
        {
          return View();
        }
</code>```

View:

```<code>@model IEnumerable<User_Manager_Interface.Models.ApplicationRole>
@{

    Layout = "~/Views/Shared/_Layout.cshtml";
}

@if (ViewBag.StatusMessage != null)
{
    if (ViewBag.StatusMessage != "")
    {
        string tmp = ViewBag.StatusMessage;
        if (tmp.Contains("error"))
        {
            <div class="notification msgerror">
                <a class="close"></a>
                <p>@ViewBag.StatusMessage</p>
            </div>
        }
        else
        {
            <div class="notification msgsuccess">
                <a class="close"></a>
                <p>@ViewBag.StatusMessage</p>
            </div>
        }
    }
}

<br />
@Html.ActionLink("Create New", "Create", "Roles", new object { }, new { @class = "stdbtn" })
<br />
<br />

<div class="contenttitle radiusbottom0">
    <h2 class="table"><span>Roles</span></h2>
</div>

<table cellpadding="0" cellspacing="0" border="0" class="stdtable" id="dyntable">
    <colgroup>
        <col class="con0" />
        <col class="con1" />
        <col class="con0" />

    </colgroup>
    <thead>
        <tr>
            <th class="head1">Name</th>
            <th class="head0">Description</th>
            <th class="head1">Options</th>

        </tr>
    </thead>
    <tfoot>
        <tr>
            <th class="head1">Name</th>
            <th class="head0">Description</th>
            <th class="head1">Options</th>
        </tr>
    </tfoot>
    <tbody>

        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.Name)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Description)
                </td>

                <td>
                    @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
                    @Html.ActionLink("Details", "Details", new { id = item.Id }) |
                    @Html.ActionLink("Delete", "Delete", new { id = item.Id })
                </td>
            </tr>
        }
    </tbody>
</table>

@section Scripts {
    @Scripts.Render("~/bundles/tables")
}
</code>```

Model:

```<code>    public class ApplicationRole : IdentityRole
    {
        [Display(Name = "Description")]
        [StringLength(100, MinimumLength = 5)]
        public string Description { get; set; }
    }
</code>```

"Error" Controller:

```<code>    public class ErrorController : Controller
    {
        //
        // GET: /Error/
        public ActionResult Index(int statusCode, Exception exception)
        {
            Response.StatusCode = statusCode;
            return View();
        }
    }
</code>```

"Error" View:

```<code>@{
    ViewBag.Title = Response.StatusCode;
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2 style="visibility:hidden">@ViewBag.Title</h2>

<div class="errorWrapper">
    <h2>An internal server error @ViewBag.Title has occurred</h2>
    <h1 class="pageErrorTitle" style="color:red">Error @ViewBag.Title - Page Not Found</h1>
    <h3 style="color:black">You may have clicked an expired link or mistyped the address.</h3>
    <br />
    <a class="default" href="javascript:history.back()">Back to Previous Page</a>   <a class="default" href="http://localhost:53648">Return to Dashboard</a>
</div>
</code>```

Please see screenshots for more visual clarity:

Update:
According to @Munzer 's answer below, I tried to change my Index action method to take in the model route value seeing as though I am passing it in my return statement. See below:

```<code>        public async Task<ActionResult> Create(ApplicationRole model)
        {

                if (ModelState.IsValid)
                {
                    var role = new ApplicationRole()
                    {
                        Name = model.Name,
                        Description = model.Description
                    };

                    var roleManager = new RoleManager<ApplicationRole>(new RoleStore<ApplicationRole>(db));
                    var result = await roleManager.CreateAsync(role);
                    if (result.Succeeded)
                    {
                        //return RedirectToAction("Index", "Roles", model);
                        return RedirectToAction("SuccessfullyAddedNewRole", "Roles", model);
                    }
                    else
                    {
                        AddErrors(result);
                    }
                }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

       public ActionResult SuccessfullyAddedNewRole(ApplicationRole model)
       {
          return View(model);
       }
</code>```

But the error still persists. I have tried everything I can think of.

答:
Solution can be found on this SO post of mine. Fixed everything :-) </p>

<p>GET http://localhost/Roles/Create 500 (Internal Server Error) </p>

Title: Object Moved Here - RedirectToAction

Body:
Again, after tiresome attempts to solve this annoying issue, I am back here. I am experiencing an "Object moved here" on my view in my MVC5 application after some return RedirectToAction("Index", "Roles", model); action on my controller.

I have considered solutions from the following links:

RedirectToAction and "Object moved to here" error

ASP.NET MVC Website: Object Moved to Here

https://forums.asp.net/t/1643235.aspx?+Object+moved+to+here+problem
but none are applicable to my problem.

Before anyone marks this as a duplicate, please consider the scenario below:

But now the weird thing is that after I have clicked on the 'here' link and it now renders my view - it has a horizontal split screen showing the correct display of my view on top and below the view that throws an Http Error Code - in this case its Error Code 500 : Internal Server Error.

The reason why I am getting the http status code error is due to this unanswered question here (one of many) :

Failed to load resource: Uncaught TypeError: $(...).select2 is not a function

But that is besides the point right now.

Controller:

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create([Bind(Include = "Name,Description")] ApplicationRole model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var role = new ApplicationRole()
                    {
                        Name = model.Name,
                        Description = model.Description
                    };

                    var roleManager = new RoleManager<ApplicationRole>(new RoleStore<ApplicationRole>(db));
                    var result = await roleManager.CreateAsync(role);
                    if (result.Succeeded)
                    {
                        return RedirectToAction("Index", "Roles", model);
                    }
                    else
                    {
                        AddErrors(result);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //Below is my index method in my Roles controller which is the action that redirection needs to route to:

        [Route("/Roles")]
        public ActionResult Index()
        {
            if (TempData["StatusMessage"] != null)
            {
                ViewBag.StatusMessage = TempData["StatusMessage"].ToString();
            }
            else
            {
                ViewBag.StatusMessage = "";
            }

            var roles = db.Roles.ToList();
            return View("Index", roles);
        }

        //GET method to create view
        public ActionResult Create()
        {
          return View();
        }

View:

@model IEnumerable<User_Manager_Interface.Models.ApplicationRole>
@{

    Layout = "~/Views/Shared/_Layout.cshtml";
}

@if (ViewBag.StatusMessage != null)
{
    if (ViewBag.StatusMessage != "")
    {
        string tmp = ViewBag.StatusMessage;
        if (tmp.Contains("error"))
        {

@ViewBag.StatusMessage

        }
        else
        {

@ViewBag.StatusMessage

        }
    }
}

@Html.ActionLink("Create New", "Create", "Roles", new object { }, new { @class = "stdbtn" })

Roles

    <colgroup>
        <col class="con0" />
        <col class="con1" />
        <col class="con0" />

    </colgroup>

            Name
            Description
            Options

            Name
            Description
            Options

        @foreach (var item in Model)
        {

                    @Html.DisplayFor(modelItem => item.Name)

                    @Html.DisplayFor(modelItem => item.Description)

                    @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
                    @Html.ActionLink("Details", "Details", new { id = item.Id }) |
                    @Html.ActionLink("Delete", "Delete", new { id = item.Id })

        }

@section Scripts {
    @Scripts.Render("~/bundles/tables")
}

Model:

    public class ApplicationRole : IdentityRole
    {
        [Display(Name = "Description")]
        [StringLength(100, MinimumLength = 5)]
        public string Description { get; set; }
    }

"Error" Controller:

    public class ErrorController : Controller
    {
        //
        // GET: /Error/
        public ActionResult Index(int statusCode, Exception exception)
        {
            Response.StatusCode = statusCode;
            return View();
        }
    }

"Error" View:

@{
    ViewBag.Title = Response.StatusCode;
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@ViewBag.Title

An internal server error @ViewBag.Title has occurred

Error @ViewBag.Title - Page Not Found

You may have clicked an expired link or mistyped the address.

    Back to Previous Page   Return to Dashboard

Please see screenshots for more visual clarity:

Update:
According to @Munzer 's answer below, I tried to change my Index action method to take in the model route value seeing as though I am passing it in my return statement. See below:

        public async Task<ActionResult> Create(ApplicationRole model)
        {

                if (ModelState.IsValid)
                {
                    var role = new ApplicationRole()
                    {
                        Name = model.Name,
                        Description = model.Description
                    };

                    var roleManager = new RoleManager<ApplicationRole>(new RoleStore<ApplicationRole>(db));
                    var result = await roleManager.CreateAsync(role);
                    if (result.Succeeded)
                    {
                        //return RedirectToAction("Index", "Roles", model);
                        return RedirectToAction("SuccessfullyAddedNewRole", "Roles", model);
                    }
                    else
                    {
                        AddErrors(result);
                    }
                }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

       public ActionResult SuccessfullyAddedNewRole(ApplicationRole model)
       {
          return View(model);
       }

But the error still persists. I have tried everything I can think of.

Body:
Solution can be found on this SO post of mine. Fixed everything :-)

GET http://localhost/Roles/Create 500 (Internal Server Error)


问:
ImportError: No module named easydict
I'm trying to run the demo of py-faster-rcnn based on this github page.
I have done all the previous steps. But When I try to run the deo with python ./tools/demo.py --gpu 0 --net vgg16 I get this error:

```<code>Traceback (most recent call last):
File "./tools/demo.py", line 17, in
from fast_rcnn.config import cfg
File "/home/hadi/Software/py-faster-rcnn/tools/../lib/fast_rcnn/config.py", line 23, in
from easydict import EasyDict as edict
ImportError: No module named easydict
</code>```

I have installed easydict with both these commands:

sudo pip install easydict

pip install easydict

Is this related to python path? I have installed both python 2.7 and 3.5. Since then I get all these python related errors. For example I have installed tensorflow for both python 2 and 3. But with python 2 it always says:

No module named tensorflow

How can I fix this?

OS: Ubuntu 16.04

答:
Try the following command in terminal :

 sudo pip2 install easydict

This worked for me well .

Title: ImportError: No module named easydict

Body:
I'm trying to run the demo of py-faster-rcnn based on this github page.
I have done all the previous steps. But When I try to run the deo with python ./tools/demo.py --gpu 0 --net vgg16 I get this error:

Traceback (most recent call last):
File "./tools/demo.py", line 17, in
from fast_rcnn.config import cfg
File "/home/hadi/Software/py-faster-rcnn/tools/../lib/fast_rcnn/config.py", line 23, in
from easydict import EasyDict as edict
ImportError: No module named easydict

I have installed easydict with both these commands:

sudo pip install easydict

pip install easydict

Is this related to python path? I have installed both python 2.7 and 3.5. Since then I get all these python related errors. For example I have installed tensorflow for both python 2 and 3. But with python 2 it always says:

No module named tensorflow

How can I fix this?

OS: Ubuntu 16.04


问:
Exposing Jenkins to the outside world to receive GitHub webhook requests
I have a Jenkins build server, and my repositories are hosted under an organization on Github.com. I would like to trigger automated builds after a push to the repository on GitHub.com. To enable this, I need to provide my Jenkins server details as a webhook in the settings of Github.com. Is it a good practice to open port 8080 from the server in the trust environment so as to be accessible from GitHub.com?</p>

答:
Yes, in order to receive incoming web hooks, you need to make an HTTP endpoint accessible to GitHub. This should only be the webhook URL instead of the complete Jenkins (filtering e.g. through a reverse proxy in front of the installation).

"Accessible to GitHub" still gives you the freedom to restrict the IP addresses that may access this endpoint. The IP addresses used by GitHub are listed here. As of now, they are in the following two networks:

192.30.252.0/22

185.199.108.0/22


问:
iOS8 + UIDeviceOrientationDidChangeNotification not getting called
In my working application (iOS 7.0.1), UIDeviceOrientationDidChangeNotification is called.

Now when i run this application in iOS 8.0 UIDeviceOrientationDidChangeNotification is not getting called.

Tried a lot but no luck.

EDIT-1:

I have use below code to add observer for orientation change. Works perfect in iOS 7. No luck for iOS 8.

```<code>[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceOrientationDidChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
</code>```

答:
Swift 3:

Add observer to UIDeviceOrientationDidChange in viewDidLoad

```<code>        NotificationCenter.default.addObserver(self, selector: #selector(orientationChanged), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
</code>```

Selector method is like this:

```<code>    func orientationChanged(notification: Notification) {

    }
</code>```

Don't forget to add Remove observer on deinit method

```<code>NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
</code>```

Body:
In my working application (iOS 7.0.1), UIDeviceOrientationDidChangeNotification is called.

Now when i run this application in iOS 8.0 UIDeviceOrientationDidChangeNotification is not getting called.

Tried a lot but no luck.

EDIT-1:

I have use below code to add observer for orientation change. Works perfect in iOS 7. No luck for iOS 8.

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceOrientationDidChange:) name:UIDeviceOrientationDidChangeNotification object:nil];

Body:
Swift 3:

Add observer to UIDeviceOrientationDidChange in viewDidLoad

        NotificationCenter.default.addObserver(self, selector: #selector(orientationChanged), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)

Selector method is like this:

    func orientationChanged(notification: Notification) {

    }

Don't forget to add Remove observer on deinit method

NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)


问:
How do I navigate from one xaml page to another, and pass values?
Somewhat related to this topic here:
Async XML Reading in Windows Phone 7

I'm developing a Windows Phone app, and I have a search function in my Search.xaml.cs file. It is called by clicking a button, it creates a search query and calls DownloadStringInBackground with it

```<code>    private void SearchQuery(object sender, EventArgs e)
    {
        string temp = "http://api.search.live.net/xml.aspx?Appid=myappid&query=randomqueryhere&sources=web";
        DownloadStringInBackground(temp);
    }

    public static void DownloadStringInBackground(string address)
    {
        WebClient client = new WebClient();
        Uri uri = new Uri(address);

        client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadStringCallback);
        client.DownloadStringAsync(uri);
    }

    private static void DownloadStringCallback(Object sender, DownloadStringCompletedEventArgs e)
    {
        // Fancy manipulation logic here

        finalResult = words;
    }
</code>```

finalResult has been stored as

```<code>public static string[] finalResult;
</code>```

in the Search class. My question is, where can I put the Navigate command (NavigationService.Navigate(new Uri("/Result.xaml", UriKind.Relative));)? I tried doing it in the callback, but I get a nullobject exception due to the static keyword. How can I ensure that finalResult has been populated, and that I can navigate to Result.xaml and reference the data in finalResult on that page. Alternately, how can I pass Words or finalResult to Result.xaml?

Thanks for looking :)

答:
If you don't make the callback function static you can do this:

```<code>Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/Result.xaml", UriKind.Relative)));
</code>```

If the callback function must be static you can use:

```<code>Deployment.Current.Dispatcher.BeginInvoke();
</code>```

Body:
Somewhat related to this topic here:
Async XML Reading in Windows Phone 7

I'm developing a Windows Phone app, and I have a search function in my Search.xaml.cs file. It is called by clicking a button, it creates a search query and calls DownloadStringInBackground with it

    private void SearchQuery(object sender, EventArgs e)
    {
        string temp = "http://api.search.live.net/xml.aspx?Appid=myappid&query=randomqueryhere&sources=web";
        DownloadStringInBackground(temp);
    }

    public static void DownloadStringInBackground(string address)
    {
        WebClient client = new WebClient();
        Uri uri = new Uri(address);

        client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadStringCallback);
        client.DownloadStringAsync(uri);
    }

    private static void DownloadStringCallback(Object sender, DownloadStringCompletedEventArgs e)
    {
        // Fancy manipulation logic here

        finalResult = words;
    }

finalResult has been stored as

public static string[] finalResult;

in the Search class. My question is, where can I put the Navigate command (NavigationService.Navigate(new Uri("/Result.xaml", UriKind.Relative));)? I tried doing it in the callback, but I get a nullobject exception due to the static keyword. How can I ensure that finalResult has been populated, and that I can navigate to Result.xaml and reference the data in finalResult on that page. Alternately, how can I pass Words or finalResult to Result.xaml?

Thanks for looking :)

Body:
If you don't make the callback function static you can do this:

Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/Result.xaml", UriKind.Relative)));

If the callback function must be static you can use:

Deployment.Current.Dispatcher.BeginInvoke();


问:
About Jasper IoT Platform
I am just bit curious. I am new in IoT and currently started working on it using ESP8266 device. I know that it needs some firmware to write and install, like smart.js.

But I have read, Jasper (http://www.jasper.com/) can connect any device and manager, monitor etc. So I am bit curious how it works internally. I am not sure whether it installs firmware created by Jasper or in other way. I was reading this article: http://www2.cumulocity.com/guides/users-guide/jasper/#link-sims

Anyone knows about this? I mean how Jasper works to connect to any devices?

答: Cisco bought Jasper, which is useful for IoT business. However it might be better way for you to check Interactor(www.interactor.com) which is great for IoT development. Interactor works to conntect to any device with any protocol. </p>

Title: About Jasper IoT Platform


问:
Extract the names of the files in folders
I'm working on a project and I'm also wondering how to extract the names of files in folders

e.g. I'm in "CatA" catalog with 2 subfolders:

"CatAA" with catalog "ExpAA" - aaa.zip inside

"CatBB" with catalog "ExpBB" - bbb.zip inside

My goal is to list (get the file names) aaa.zip and bbb.zip file while being in a main "CatA" file.

```<code>string[] dirs = Directory.GetDirectories(@"C:\CatA");

        //checkedListBox1.Items.Insert(0, dirs.Length);

        for (int i = 0; i < dirs.Length - 1; i++)
        {
          //c# go a folder up
          dirs.
          var zipFiles = Directory.GetFiles(@"C:\Users\DLXP3B3\Desktop\tes", "*.zip");
          checkedListBox1.Items.Insert(i, zipFiles[i]);
        }
</code>```

I have some work done, but I don't know how to proceed. Any ideas would be appreciated. Thank you.

答:
Actually the Directory.GetFiles gives you the path of matching files, If you want the file names alone you have to get the file names,

```<code>var zipFiles = System.IO.Directory.GetFiles(@"C:\CatA", "*.zip", System.IO.SearchOption.AllDirectories)
                                  .Select(x=> Path.GetFileName(x))
                                  .ToArray();
</code>```

Now the zipFiles will have the list of all files with extension .zip

Body:
I'm working on a project and I'm also wondering how to extract the names of files in folders

e.g. I'm in "CatA" catalog with 2 subfolders:

"CatAA" with catalog "ExpAA" - aaa.zip inside

"CatBB" with catalog "ExpBB" - bbb.zip inside

My goal is to list (get the file names) aaa.zip and bbb.zip file while being in a main "CatA" file.

string[] dirs = Directory.GetDirectories(@"C:\CatA");

        //checkedListBox1.Items.Insert(0, dirs.Length);

        for (int i = 0; i < dirs.Length - 1; i++)
        {
          //c# go a folder up
          dirs.
          var zipFiles = Directory.GetFiles(@"C:\Users\DLXP3B3\Desktop\tes", "*.zip");
          checkedListBox1.Items.Insert(i, zipFiles[i]);
        }

I have some work done, but I don't know how to proceed. Any ideas would be appreciated. Thank you.

Body:
Actually the Directory.GetFiles gives you the path of matching files, If you want the file names alone you have to get the file names,

var zipFiles = System.IO.Directory.GetFiles(@"C:\CatA", "*.zip", System.IO.SearchOption.AllDirectories)
                                  .Select(x=> Path.GetFileName(x))
                                  .ToArray();

Now the zipFiles will have the list of all files with extension .zip